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

标签 c++ function templates functor

<分区>

我目前有一个带有模板方法的模板类。与仿函数一起工作很好,但在编译函数时遇到问题。

Foo.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 */ }

main.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>);

关于c++ - 在 C++ 中使用模板化方法交替传递仿函数和函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12944703/

相关文章:

c++ - 指针,将参数传递给 main 和段错误

C++函数通过引用输入参数与通过指针输入参数

c++ - 使用模板函数的不同类型的输入

PHP 模板方法 <?=$var?>?

c++ - 拆分大文件

由于 Cmake 检查,Android NDK 项目需要数年时间才能完成 gradle buid

Javascript 模态窗口例程每次点击都会执行更多时间

c++ - 递归函数的正确返回方式

c++ - 为什么模板参数推导不适用于仅指定前两个参数的可变参数模板类?

c++ - 路径不对,怎么办?