c++ - 如何typedef模板函数指针?

标签 c++ c++11 templates function-pointers typedef

我想定义一个指向模板函数的函数指针

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/

相关文章:

c++ - ubuntu命令获取C++程序中的所有功能

c++ - 需要优化 - 算法实现占用太多内存

c++ - 如何获得项目中所有 UClass 的列表(蓝图和 C++)

c++ - 对齐对 C++11 中的性能真的很重要吗?

C++ 11 动态数组部分列表初始化(错误或误解)?

c++ - 如何防止特定模板的隐式模板实例化?

c++ - 在模板类中使用非模板函数

c++ - 枚举和索引所有可能的 n 个顶点的树

c++ - 如何根据元素数量终止可变参数模板递归?

c++ - 访问不完整类型的成员类型