简体   繁体   English

C ++ lambda转换 - 为什么候选构造函数不可行:没有已知的从lambda到std :: function的转换

[英]C++ lambda conversion — why is candidate constructor not viable: no known conversion from lambda to std::function

Question about implicit lambda conversions. 关于隐式lambda转换的问题。 I have this type: 我有这种类型:

class A {
 public:
  A(std::function<void(std::string)> func) {
    ....
  }
};

Which I believe has a valid copy constructor. 我相信它有一个有效的复制构造函数。

As I would like to do the following 我想做以下几点

A a = [](std::string param) { ... };

Or 要么

void MyFunc(A a) { ... }  // definition

MyFunc([](std::string param) { ... });  // call

Yet both these yield compile error: 然而这两个产生编译错误:

note: candidate constructor not viable: no known conversion from '(lambda at ....)' to 'std::function' for 1st argument 注意:候选构造函数不可行:第一个参数没有从'(lambda at ....)'到'std :: function'的已知转换

Why is this? 为什么是这样? Or should this be possible? 或者这可能吗?

Your problem is that only one user conversion is allowed and you need two: 您的问题是只允许一次用户转换,您需要两个:

  • lamba -> std::function -> A . lamba - > std::function - > A

Both

A a{[](std::string) {}};
MyFunc({[](std::string) {}});

work. 工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM