C ++ 11 lambda作为成员变量? [英] C++11 lambda as member variable?
问题描述
可以将lambda定义为类成员吗?
Can lambda's be defined as class members?
例如,是否可以使用lambda而不是函数对象重写下面的代码示例? p>
For example, would it be possible to rewrite the code sample below using a lambda instead of a function object?
struct Foo {
std::function<void()> bar;
};
我不知道的原因是因为以下lambda可以作为参数传递:
The reason I wonder is because the following lambda's can be passed as arguments:
template<typename Lambda>
void call_lambda(Lambda lambda) // what is the exact type here?
{
lambda();
}
int test_foo() {
call_lambda([]() { std::cout << "lambda calling" << std::endl; });
}
我想如果一个lambda可以作为一个函数参数传递,
I figured that if a lambda can be passed as a function argument then maybe they can also be stored as a member variable.
更多的修补后,我发现这是有效的(但它是无意义的):
After more tinkering I found that this works (but it's kind of pointless):
auto say_hello = [](){ std::cout << "Hello"; };
struct Foo {
typedef decltype(say_hello) Bar;
Bar bar;
Foo() : bar(say_hello) {}
};
推荐答案
模板可以没有类型擦除, :
Templates make it possible without type erasure, but that's it:
template<typename T>
struct foo {
T t;
};
template<typename T>
foo<typename std::decay<T>::type>
make_foo(T&& t)
{
return { std::forward<T>(t) };
}
// ...
auto f = make_foo([] { return 42; });
重复每个人都已经暴露的参数: [] {} code>不是一个类型,所以你不能使用它作为eg您正在尝试的模板参数。使用
decltype
也是iffy,因为lambda表达式的每个实例都是具有唯一类型的单独的闭包对象的符号。 (例如,上面的 f
的类型不是 foo< decltype([] {return 42;})> / code>。)
Repeating the arguments that everyone has already exposed: []{}
is not a type, so you can't use it as e.g. a template parameter like you're trying. Using decltype
is also iffy because every instance of a lambda expression is a notation for a separate closure object with a unique type. (e.g. the type of f
above is not foo<decltype([] { return 42; })>
.)
这篇关于C ++ 11 lambda作为成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!