use*_*020 7 c++ templates function-pointers
是否可以使用通用函数指针作为模板参数?函数指针模板可以接受自由函数,成员函数和lambda函数.为简单起见,假设函数只有一个参数,比如
template<class ArgumentT, class ReturnT, function* f>
struct A
{
// f is used somewhere.
};
Run Code Online (Sandbox Code Playgroud)
普通模板参数可以引用一个函数.
#include <iostream>
template <class ArgT, class RetT, class F>
struct A {
F f;
public:
A(F f) : f(f) {}
RetT operator()(ArgT arg) { return f(arg); }
};
int unchanged(int i) { return i; }
int main(){
A < int, int, int(*)(int)> t{ unchanged };
for (int i = 0; i < 10; i++)
std::cout << t(i) << "\n";
}
Run Code Online (Sandbox Code Playgroud)
没有什么限制函数的模板参数 - 你可以轻松地使用一些重载的类operator(),并调用它(事实上,这通常是更好的).