【问题标题】:Wrap overloaded function via std::function通过 std::function 包装重载函数
【发布时间】:2012-04-11 17:35:03
【问题描述】:

我有一个重载的函数,我想传递它,包裹在 std::function 中。 GCC4.6 没有找到“匹配函数”。 虽然我确实在这里找到了一些问题,但答案并不像我希望的那样清楚。有人能告诉我为什么下面的代码不能扣除正确的重载以及如何(优雅地)解决它吗?

int test(const std::string&) {
    return 0;
}

int test(const std::string*) {
    return 0;
}

int main() {
    std::function<int(const std::string&)> func = test;
    return func();
}

【问题讨论】:

    标签: c++ c++11 overloading


    【解决方案1】:

    这是模棱两可的情况。

    为了消除歧义,使用显式转换为:

    typedef int (*funtype)(const std::string&);
    
    std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!
    

    现在编译器将能够根据转换中的类型来消除歧义。

    或者,您可以这样做:

    typedef int (*funtype)(const std::string&);
    
    funtype fun = test; //no cast required now!
    std::function<int(const std::string&)> func = fun; //no cast!
    

    那么为什么std::function&lt;int(const std::string&amp;)&gt; 不能像上面的funtype fun = test 那样工作?

    答案是,因为std::function 可以用任何对象初始化,因为它的构造函数是模板化的,它独立于您传递给std::function 的模板参数。

    【讨论】:

    • 请使用static_cast 代替老式演员表。
    • @Anonymous:是的。但我想让它简短。无论如何,我对其进行了编辑,使其看起来像 C++ 风格!
    • 多么讽刺——你必须使用函数指针来获得一个 std::function,这是为了摆脱函数指针而引入的:) thx
    • @LCIDFire: std::function 不是为了摆脱函数指针而引入的,而是为了提供更通用的解决方案。您可以使用std::function 并使用任何函数指针、lambda、仿函数(包括绑定器)...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 2014-08-11
    • 2011-06-11
    相关资源
    最近更新 更多