使用boost::函数绑定到重载方法
bind to overloaded method using boost::function
如何实现以下重载方法调用
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
)。
相关文章:
- 重载方法的方式会在使用临时调用时生成编译器错误
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 使用 nullptr 调用重载方法是不明确的
- 具有重载方法的可变参数数据结构
- C++11 重载方法,并转发到唯一方法
- 获取特定的模板重载方法指针
- std::result_of 应用于 const 重载方法
- 重载方法的类接受模板和基类 - 如何默认某个方法
- 推导模板类重载方法的地址会导致"error: expected primary-expression before ‘decltype’"
- C++如何使用按值传递和按引用传递的重载方法
- 具有原始方法参数派生类的 C++ 重载方法参数
- SWIG:在派生类中处理基类重载方法
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- C++选择'wrong'默认参数的重载方法
- 重写重载方法会隐藏一些重载
- 在C++中,如何从父类变量的子类调用重载方法
- 所有重载方法的别名
- 使用 SWIG 在重载C++方法中设置类型