如何使用指向静态成员函数的函数指针作为模板参数?

Sve*_*ach 12 c++ templates function-pointers

这段代码

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() {}
Run Code Online (Sandbox Code Playgroud)

导致以下错误消息(gcc 4.4.5):

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

执行以下任一操作后,错误消失:

  1. call使用A::或限定模板参数A<T>::,即使用call<A::static_func>()而不是call<static_func>().

  2. 删除模板参数A,即创建A非模板类.

  3. 创建static_func()一个全局函数(使用外部链接).

为什么上面的代码错了?为什么上面提到的修复工作?特别是1和2对我来说似乎很奇怪.从错误消息判断,额外的限定似乎不提供编译器不知道的任何信息.