在C++中使用模板化方法交替传递函子和函数指针

Passing functors and function pointers interchangeably using a templated method in C++

本文关键字:指针 函数 方法 C++      更新时间:2023-10-16

我目前有一个模板化类,带有模板化方法。与函子配合使用很好,但在编译函数时遇到问题。

福.h

template <typename T>
class Foo {
   public:
   // Constructor, destructor, etc...
   template <typename Func>
   void bar(T x, Func f);
};
template <typename T>
template <typename Func>
void Foo<T>::bar(T x, Func f) { /* some code here */ }

主.cpp

#include "Foo.h"
template <typename T>
class Functor {
    public:
    Functor() {}
    void operator()(T x) { /* ... */ }
    private:
    /* some attributes here */
};
template <typename T>
void Function(T x) { /* ... */ } 
int main() {
   Foo<int> foo;
   Functor<int> F;
   foo.bar(2, F); // No problem
   foo.bar(2, Function); // <unresolved overloaded function type>
   return 0;
}

如果要获取重载函数的函数指针,则需要告诉系统您想要的重载集中的哪个函数:

foo.bar(2, static_cast<void(*)(int)>(&Function);

在引用的情况下,函数实际上是一个模板,即,您也可以直接引用其专用化:

foo.bar(2, &Function<int>);