【问题标题】:Is it possible to define the type for "template function pointer"?是否可以定义“模板函数指针”的类型?
【发布时间】:2014-03-14 16:13:54
【问题描述】:

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

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&lt;99&gt;()),但不能使用参数foo&lt;99&gt; 调用test_foo()

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

有没有办法可以像test_foo(Foo&lt;99&gt;())一样从参数foo&lt;99&gt;中获取test_foo()中的模板参数N

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

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

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

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

    这对于类模板是不同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多