简体   繁体   English

构造std :: function的向量时发生编译器错误

[英]Compiler error when constructing a vector of std::function

Please can someone help explain why I get an error when compiling the following code using Xcode 5.1 on OS X. Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn). 请有人帮忙解释为什么在OS X上使用Xcode 5.1编译以下代码时会出错。Apple LLVM版本5.1(clang-503.0.40)(基于LLVM 3.4svn)。

#include <vector>
#include <functional>

void func1(const std::string& value)
{
    // ...
}

void func2(const std::string& value, int min, int max)
{
    // ...
}

class X
{
public:
    void x1(const std::string& value)
    {
        // ...
    }

    void x2(const std::string& value, int min, int max)
    {
        // ...
    }
};

const std::vector<std::function<void(std::string)>> functions
{
    func1,
    std::bind(func2, std::placeholders::_1, 5, 6),
    std::mem_fn(&X::x1),                                // compiler error
};

The error reported is: 报告的错误是:

no matching constructor for initialization of 'const std::vector<std::function<void (std::string)> >'
const std::vector<std::function<void(std::string)>> functions

Furthermore, I would like to add X::x2 to the vector. 此外,我想将X :: x2添加到向量中。 How would I do that? 我该怎么做?

Thanks. 谢谢。

What std::mem_fn does, it returns some unspecified object callable with an additional first argument of a pointer or reference type (or even a smart pointer type) same as the type that member function or member variable that is passed in belongs to (all other arguments are forwarded). 什么std::mem_fn做,它返回一些未指定的对象与指针或引用类型的附加第一自变量调用(或甚至一个智能指针型)相同的类型,其在通过成员函数或成员变量属于(所有其他参数将被转发)。 That means you could store that object in a function wrapper like below: 这意味着您可以将该对象存储在如下的函数包装中:

std::function<void(X*,const std::string&)> f = std::mem_fn(&X::x1);

and then call it with an actual argument: 然后使用实际参数调用它:

X x{};
f(&x, "foo"); // or std::mem_fn(&X::x1)(&x, "foo");

which is same as: 与以下内容相同:

(&x)->x1("foo");

In other words, this is most probably not what you wanted while storing that callable object in a std::vector of std::function<void(const std::string&)> . 换句话说,在将可调用对象存储在std::function<void(const std::string&)>std::vector中)时,这可能不是您想要的。 Instead of adding the additional first argument, you should rather bind it with a context for which that function will be invoked: 与其添加其他第一个参数,不如将其绑定到将为其调用该函数的上下文:

X x{}; // object in context of which the function will be called

const std::vector<std::function<void(std::string)>> functions
{
    func1,
    std::bind(func2, std::placeholders::_1, 5, 6),
    std::bind(&X::x1, &x, std::placeholders::_1),
//  ~~~~~~~~^ ~~~~~^  ~^            ~~~~~~~~~~^
//     bind  function with object x and actual argument to be forwarded
};

DEMO DEMO

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

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