gpt4 book ai didi

c++ - 函数指针作为模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:10 24 4
gpt4 key购买 nike

如何将函数指针写成模板?

template <typename T>
T (*PtrToFunction)(T a);

最佳答案

我假设您正在尝试声明一个类型(您不能声明没有具体类型的“模板变量”)。

C++03 没有模板类型定义,您需要使用结构作为解决方法:

template <typename T>
struct FuncPtr {
typedef T (*Type)(T a);
};

...

// Use template directly
FuncPtr<int>::Type intf;

// Hide behind a typedef
typedef FuncPtr<double>::Type DoubleFn;
DoubleFn doublef;

C++11 模板别名将消除 struct 解决方法,但目前除了 Clang 之外没有编译器实际执行此操作。

template <typename T>
typedef T (*FuncPtr)(T a);

// Use template directly
FuncPtr<int> intf;

// Hide behind a typedef
typedef FuncPtr<double> DoubleFn;
DoubleFn doublef;

关于c++ - 函数指针作为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com