【问题标题】:bind to overloaded method using boost::function使用 boost::function 绑定到重载方法
【发布时间】:2013-08-01 15:43:40
【问题描述】:

如何实现下面的重载方法调用

class Foo {
    void bind(const int,boost::function<int (void)> f);
    void bind(const int,boost::function<std::string (void)> f);
    void bind(const int,boost::function<double (void)> f);
};

第一次尝试

SomeClass c;
Foo f;
f.bind(1,boost::bind(&SomeClass::getint,ref(c));
f.bind(1,boost::bind(&SomeClass::getstring,ref(c)));
f.bind(1,boost::bind(&SomeClass::getdouble,ref(c)));

然后我找到了possible answer,所以尝试了这个:-

f.bind(static_cast<void (Foo::*)(int,boost::function<int(void)>)>(1,boost::bind(&SomeClass::getint)));

看起来很丑但可能有用?

但给出错误

error C2440: 'static_cast' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'void (__cdecl Foo::* )(int,boost::function<Signature>)'

我可以使这种重载工作的任何想法。我怀疑正在发生类型擦除,但编译器显然可以识别重载方法,因为 Foo.cpp 编译得很好

【问题讨论】:

    标签: c++ function boost bind


    【解决方案1】:

    您链接到的可能答案是解决一个不同的问题:在获取指向该函数的指针时在函数重载之间进行选择。解决方案是显式转换为正确的函数类型,因为只有正确的函数才能转换为该类型。

    您的问题不同:在调用函数时在重载之间进行选择,此时没有明确转换为任何重载参数类型。您可以显式转换为函数类型:

    f.bind(1,boost::function<int (void)>(boost::bind(&SomeClass::getint,boost::ref(c))));
    

    或者,在 C++11 中,使用 lambda:

    f.bind(1,[&]{return c.getint();});
    

    (在 C++11 中,您可能更喜欢 std::function 而不是 boost::function)。

    【讨论】:

    • 完美运行,是的,我切换到 std::function。我猜没有办法让编译器通过使用工厂函数来推断转换参数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 2016-03-16
    相关资源
    最近更新 更多