这行得通..。
auto x = 4;
typedef decltype(x) x_t;
x_t y = 5;..。那么为什么这个不起作用呢?
int j = 4;
auto func = [&] (int i) { cout << "Hello: i=" << i << " j=" << j << endl;};
typedef decltype(func) lambda_t;
lambda_t func2 = [&] (int i) { cout << "Bye: i=" << i << " j=" << j << endl;};..。如何使用std::function手动声明lambda_t?
发布于 2012-11-30 02:07:40
...那么,为什么这不起作用呢?
因为lambda的每个词法实例都有不同的类型。如果使用相同的字符,这并不重要。
..如何使用std::function手动声明lambda_t?
lambda接受一个int参数,不返回任何内容...因此:
typedef std::function<void(int)> lambda_t;发布于 2012-11-30 02:10:13
Lambda类型是无法表达的(无法命名),这就是你不能做你所要求的事情的原因。除此之外,每个lambda都是不同的类型,所以即使您可以命名该类型,您也无法将第二个lambda赋给第一个lambda。如果您将lambda语法看作是函数对象的快捷方式,就会变得更加清晰:每个lambda的成员operator()都不同,因此它们的类型也不同。
另一方面,您可以将lambda赋值给具有适当签名的std::function<>对象,在您的示例中,签名应该是std::function<void(int)>。
发布于 2015-04-25 08:01:07
这里有一些确凿的证据证明这是行不通的。类似的场景:
int foo = 3;
int bar = 3;
std::cout << (typeid(foo).hash_code() == typeid(bar).hash_code()); // prints one -- obviously - they are the same type现在,让我们使用完全相同的代码,但是使用lambdas。你认为会有什么样的反应。
auto foo = [](){std::cout << "HELLO\n"; };
auto bar = [](){std::cout << "HELLO\n"; };
std::cout << (typeid(foo).hash_code() == typeid(bar).hash_code()); // prints 0 -- different type even though they are declared exactly the same.https://stackoverflow.com/questions/13631890
复制相似问题