songyuanyao
songyuanyao

Reputation: 173014

Is it possible to define the type for "template function pointer"?

Is it possible to define the type for "template function pointer"? Such as

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

just as the template class can do:

Someclass<99>();

To explain my problem further, I have the following code:

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; }

I can call test_foo(Foo<99>()), but can't call test_foo() with the argument 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

Is there an approach can get the template parameter N in test_foo() from the argument foo<99> just like test_foo(Foo<99>()) do?

Upvotes: 0

Views: 92

Answers (1)

sehe
sehe

Reputation: 393769

You can in C++11 with template aliases:

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

You cannot do "traits" on those fptr values (or deduce the template arguments from a &foo<N> function parameter), because the value of a function template instantiation does not encode the template arguments into the resultant type.

This is different for class templates.

Upvotes: 1

Related Questions