在C++中使用模板化方法交替传递函子和函数指针
Passing functors and function pointers interchangeably using a templated method in C++
我目前有一个模板化类,带有模板化方法。与函子配合使用很好,但在编译函数时遇到问题。
福.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>);
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址