我想定义一个指向模板函数的函数指针。
class A
{
template <typename T>
typedef void (*FPTR)<T>();
}
我试过这种方式,没有成功。对这件事有什么想法吗?
最佳答案
正如@HolyBlackCat 所指出的,正常的函数指针应该可以工作,因为您有一个简单的模板化 void 函数,其模板参数不会作用于返回和参数类型。
template <typename T>
void someVoidFunction() {}
using fPtrType = void(*)();
int main()
{
fPtrType funPtr1 = &someVoidFunction<int>;
fPtrType funPtr2 = &someVoidFunction<float>;
fPtrType funPtr3 = &someVoidFunction<std::string>;
return 0;
}
如果是这样的话,模板参数取决于函数 arg 和返回类型,您也应该为每种类型实例化函数指针。
template <typename T, typename U>
T someFunction(U u) {}
template <typename T, typename U>
using fPtrType = T(*)(U);
int main()
{
fPtrType<int, float> funPtr1 = &someFunction<int, float>; // instance 1
fPtrType<float, float> funPtr2 = &someFunction<float, float>; // instance 2
return 0;
}
关于c++ - 如何typedef模板函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53030633/