Sven Marnach
Sven Marnach

Reputation: 601799

How to use a function pointer to a static member function as a template parameter?

This code

template <void (*func)()>
static void call() { func(); }

template <typename T>
struct A {
    A() { call<static_func>(); }   // <--- error
    static void static_func() {}
};

A<int> a;

int main() {}

results in the following error message (gcc 4.4.5):

test.cc:6: error: 'static void A<T>::static_func() [with T = int]'
                   cannot appear in a constant-expression

The error disappears after doing either of the following:

  1. Qualify the template parameter of call with A:: or A<T>::, i.e. use call<A::static_func>() instead of call<static_func>().

  2. Remove the template parameter of A, i.e. make A a non-template class.

  3. Make static_func() a global function (with external linkage).

Why is the above code wrong? And why do the mentioned fixes work? Especially 1 and 2 seem very strange to me. Judging from the error message, the extra qualification doesn't seem to provide any information the compiler doesn't know anyway.

Upvotes: 11

Views: 727

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254501

This is a bug in GCC.

Upvotes: 4

Related Questions