c++ - 是否可以定义 "template function pointer"的类型?

标签 c++ templates

是否可以为“模板函数指针”定义类型?比如

void (*tfp<99>)(); // can't compile

就像模板类可以做的那样:

Someclass<99>();

为了进一步解释我的问题,我有以下代码:

template <int N>
class Foo {};

template <int N>
void foo() {}

template <int N, template <int> class OP>
void test_foo(OP<N> op) { std::cout << N << std::endl; }

我可以打电话test_foo(Foo<99>()) , 但不能调用 test_foo()使用参数 foo<99> :

test_foo(Foo<99>());                    //OK
test_foo(foo<99>);                      //error: candidate template ignored: could not match '<N>' against 'void (*)()'
test_foo<void (*)()>(foo<99>);          //error: candidate template ignored: invalid explicitly-specified argument for template parameter 'N'
test_foo<void (*<99>)()>(foo<99>);      //error: expected expression
test_foo<void (*<99>)()<99> >(foo<99>); //error: expected expression

有没有办法可以得到模板参数Ntest_foo()从参数 foo<99>就像test_foo(Foo<99>())做什么?

最佳答案

您可以在 C++11 中使用模板别名:

template <int V> using fptr = void (*tfp<V>)();

您不能对这些 fptr 值执行“特征”(或从 &foo<N> 函数参数推导模板参数),因为函数模板实例化的值 将模板参数编码为结果类型。

这对于类模板是不同的。

关于c++ - 是否可以定义 "template function pointer"的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22398603/

相关文章:

python - Django:is_authenticated 和 is_anonymous 在注销后都返回 true

c++ - 不匹配 operator= 错误

c++ - GCC:函数包装器模板问题

c++ - 对 WinMain Example 返回类型感到困惑

c++ - 如果存在堆栈溢出的可能性,为什么还要使用堆栈

c++ -::createFile winApi 失败并出现错误 5 (access_denied)。是 shell 编程还是其他解决方案或任何提示。

c++ - 我可以以某种方式公开模板模板参数吗?

c++ - 一个类对象到另一个数据类型?

c++ - 为什么 C++20 范围不只提供管道语法?

c++ - 如果类具有基于模板参数的成员,我可以自定义吗?