c++ - C++ 编译器如何决定调用这些函数中的哪一个?

标签 c++ templates functor

考虑以下设置:

我有一个接口(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/

相关文章:

c++ - 与调度相关的死锁

c++ - C microshell 有一个参数的段错误,但没有两个

c++ - 结构相同的专业

haskell - Haskell中通用多态ADT的仿函数实例?

c++ - 在运行时定义 C++ 函数

C++ Win32——COM 方法 : equivalent C declaration

c++ - 使用 string_view 进行 map 查找

c++ - 将 operator== 重载为带有模板参数的自由函数的语法是什么?

c++ - 这些链接错误是什么意思? (C++)(MSVC++)

haskell - Haskell 中的索引仿函数到底是什么,它的用途是什么?