我可以在范围内创建指向模板函数的指针吗?

can I create a pointer to a templated function inside a scope?

我想创建一个指向模板函数的指针:

template <class T>
void foo(T x){}

int main()
{


template <class T>
void (*ptr)(T);


    return 0;
}

我得到上面的错误:error C2951: template declarations are only permitted at global or namespace scope

所以我可以通过在全局范围内声明指向模板函数的指针来修复它并且它工作正常:

template <class T>
void foo(T x){ cout << "foo()" << endl;}

template <class T>
void (*ptr)(T);


int main()
{

    ptr = foo;
    (*ptr)(7);

    return 0;
}

一个function-template不是一个函数。而function-pointers只能赋值给匹配签名的函数

在此声明中:

template <class T>
void foo(T x){ cout << "foo()" << endl;}

foo 是一个 function-template。直到它被实例化后才会产生一个函数。因此,您只能获得指向 foo.

实例化的函数指针

假设您有一个函数指针 Ktr,您只能将其分配给 foo 的实例化,如下所示:

void (*Ktr)(int);
Ktr = foo<int>;

在此声明中:

template <class T>
void (*ptr)(T);

您声明了一个 variable template (C++14) 函数指针类型,将类型 T 的对象作为唯一参数。