C++ 使用boost::函数绑定到重载方法
如何实现以下重载方法调用C++ 使用boost::函数绑定到重载方法,c++,function,boost,bind,C++,Function,Boost,Bind,如何实现以下重载方法调用 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); }; 然后我找到了一个非常尝试的方法:- f.bind
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);
};
然后我找到了一个非常尝试的方法:-
f.bind(static_cast<void (Foo::*)(int,boost::function<int(void)>)>(1,boost::bind(&SomeClass::getint)));
f.bind(static_cast(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>)'
error C2440:“static_cast”:无法从“boost::_bi::bind_t”转换为“void(u cdecl Foo::*)(int,boost::function)”
我有什么想法可以让这个超负荷工作。我怀疑正在发生类型擦除,但编译器显然能够识别重载方法,因为Foo.cpp编译得很好您链接到的可能答案是解决一个不同的问题:在获取指向该函数的指针时在函数重载之间进行选择。解决方案是显式转换为正确的函数类型,因为只有正确的函数才能转换为该类型 您的问题是不同的:在调用函数时选择重载,在没有明确转换到任何重载参数类型时选择重载。您可以显式转换为函数类型:
f.bind(1,boost::function<int (void)>(boost::bind(&SomeClass::getint,boost::ref(c))));
(你可能更喜欢C++11中的
std::function
而不是boost::function
。工作得很好,是的,我切换到了std::function。我猜没有办法让编译器通过使用工厂函数来推断强制转换参数?
f.bind(1,boost::function<int (void)>(boost::bind(&SomeClass::getint,boost::ref(c))));
f.bind(1,[&]{return c.getint();});