Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
Sven Marnach Avatar asked Nov 14 '11 15:11

Sven Marnach


1 Answers

This is a bug in GCC.

like image 173
Mike Seymour Avatar answered Oct 25 '22 12:10

Mike Seymour