接受对任何类型的可变引用的 Lambda
Lambda that accepts a mutable reference to any type
我知道 auto
关键字可用于获取接受任何类型的 lambda 函数。例如,可以这样做:
auto my_lambda = [](auto & anything)
{
std :: cout << anything << std :: endl;
}
然后像 my_lambda(my_string)
一样调用 my_lambda(my_int)
。但是,据我所知,lambda also 接受 const 对象。换句话说,如果我调用 my_lambda(3)
,auto
将被替换为 const int
,并且 my_lambda
现在将接受对 const int
.[=21 的引用=]
现在,我可以通过添加const
关键字来指定:I want it const!,如下:
auto my_lambda = [](const auto & anything)
{
std :: cout << anything << std :: endl;
}
但我似乎找不到任何方法来指定:我希望它可变!有什么可以说服 lambda 函数接受对任意类型的引用,但仅可变的?
只需添加一个静态断言:
#include <iostream>
#include <type_traits>
int main()
{
auto my_lambda
{
[](auto & anything)
{
static_assert(!::std::is_const_v<::std::remove_reference_t<decltype(anything)>>);
std :: cout << anything << std :: endl;
}
};
int bar{};
my_lambda(bar);
int const foo{};
my_lambda(foo); // error
}
如果提供了 const
类型,您可以将 static_assert
与 std::is_const
结合使用来生成编译器错误。例如:
#include <iostream>
#include <type_traits>
int main()
{
auto my_lambda = [](auto & anything)
{
using input_type = std::remove_reference_t<decltype(anything)>;
static_assert(std::is_const_v<input_type> == false, "Can't pass a const.");
std::cout << anything << std::endl;
};
int i = 5;
const int j = 10;
my_lambda(i);
my_lambda(j); // error: static assertion failed: Can't pass a const.
}
我知道 auto
关键字可用于获取接受任何类型的 lambda 函数。例如,可以这样做:
auto my_lambda = [](auto & anything)
{
std :: cout << anything << std :: endl;
}
然后像 my_lambda(my_string)
一样调用 my_lambda(my_int)
。但是,据我所知,lambda also 接受 const 对象。换句话说,如果我调用 my_lambda(3)
,auto
将被替换为 const int
,并且 my_lambda
现在将接受对 const int
.[=21 的引用=]
现在,我可以通过添加const
关键字来指定:I want it const!,如下:
auto my_lambda = [](const auto & anything)
{
std :: cout << anything << std :: endl;
}
但我似乎找不到任何方法来指定:我希望它可变!有什么可以说服 lambda 函数接受对任意类型的引用,但仅可变的?
只需添加一个静态断言:
#include <iostream>
#include <type_traits>
int main()
{
auto my_lambda
{
[](auto & anything)
{
static_assert(!::std::is_const_v<::std::remove_reference_t<decltype(anything)>>);
std :: cout << anything << std :: endl;
}
};
int bar{};
my_lambda(bar);
int const foo{};
my_lambda(foo); // error
}
如果提供了 const
类型,您可以将 static_assert
与 std::is_const
结合使用来生成编译器错误。例如:
#include <iostream>
#include <type_traits>
int main()
{
auto my_lambda = [](auto & anything)
{
using input_type = std::remove_reference_t<decltype(anything)>;
static_assert(std::is_const_v<input_type> == false, "Can't pass a const.");
std::cout << anything << std::endl;
};
int i = 5;
const int j = 10;
my_lambda(i);
my_lambda(j); // error: static assertion failed: Can't pass a const.
}