简体   繁体   English

std :: function std :: bind与lambda重载歧义

[英]std::function std::bind with lambda overload ambiguity

Consider the following code 考虑以下代码

class my_class {
public:
struct my_struct {
   int i;
};
std::function<void(my_struct&)> func;
my_class() {
   func = std::bind([this](my_struct& s) { s.i = 5; });
}
};

On VS 2017 I am receiving the following errors: 在VS 2017上,我收到以下错误:

error C2440: 'initializing': cannot convert from 'std::_Binder>' to 'std::function' note: No constructor could take the source type, or constructor overload resolution was ambiguous 错误C2440:“正在初始化”:无法从“ std :: _ Binder>”转换为“ std :: function”注意:没有构造函数可以采用源类型,否则构造函数重载解析度不明确

Any thoughts on what I'm missing to resolve the ambiguity? 关于我想解决的歧义有什么想法?

This is about the most unhelpful compiler error ever. 这是有史以来最无用的编译器错误。 The problem is that you want 问题是你想要

func = std::bind([this](my_struct& s) { s.i = 5; }, std::placeholders::_1);
//                                                  ^^^^^^^^^^^^^^^^^^^^^

std::bind(f) means "give me a g such that g(/* anything */) is f() . std::bind(f)意思是“给我一个g ,使得g(/* anything */)f()

You need to use placeholders if you want to pass arguments through. 如果要传递参数,则需要使用占位符。

(I assume that your real code does something more complicated than this, because there's no need for bind or for capturing this in the code you've shown.) (我假设你真正的代码做一些事情比这更复杂,因为没有必要bind或捕获this中还有你的代码。)

std::bind is more or less obsolete in C++11. std::bind在C ++ 11中或多或少已经过时。 Just use a lambda instead. 只需使用lambda即可。

class my_class
{
public:
  struct my_struct {
    int i;
  };
  my_class()
  : func ([](my_struct& s) { s.i = 5; }) {}
private:
  std::function<void(my_struct&)> func;
};

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

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