使用boost::函数绑定到重载方法

bind to overloaded method using boost::function

本文关键字:重载 方法 函数 boost 使用 绑定      更新时间:2023-10-16

如何实现以下重载方法调用

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)));

然后我找到了一个可能的答案,所以尝试了这个:-

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编译了精细的

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

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

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)。