考虑以下设置:
我有一个接口(interface)
template<class T>
void FooClass<T>::foo(boost::function<double (int)> f)
{...}
我想使用 Functor 实现 f:
class MyFun {
public: double operator()(int a) {do something...;}
}
但是接口(interface)中定义了另一个函数
template<class T>
template <class FunPtr>
void FooClass<T>::foo(const FunPtr& f)
{...}
当一个 FooClass 对象被调用时,
MyFun f;
FooClass<double> fooclass;
fooclass.foo(f);
它使用第二个定义,而我希望它调用第一个 - 这可以以某种方式改变吗?
最佳答案
编译器“更喜欢”第二个定义,因为模板版本导致函数对象参数精确匹配,而boost::function
参数需要一个隐式转换被接受(并且隐式转换被认为在直接重载解析之后) .您只需构造一个 boost::function
对象,然后然后将它传递给该函数即可实现您想要的(请注意,您可以在同一行中执行此操作,我为了清楚起见,我只是单独进行):
boost::function<double (int)> bMyFun(myFunInstance);
fooClassInstance.foo(bMyFun);
关于c++ - C++ 编译器如何决定调用这些函数中的哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7105380/