C++,函数指针到模板函数指针

Ian*_*Ian 21 c++ templates function-pointers

我有一个指向常见静态方法的指针

class MyClass
{
  private:
    static double ( *pfunction ) ( const Object *, const Object *);
    ...
};
Run Code Online (Sandbox Code Playgroud)

指向静态方法

 class SomeClass
 {
  public:
    static double getA ( const Object *o1, const Object *o2);
    ...
 };
Run Code Online (Sandbox Code Playgroud)

初始化:

double ( *MyClass::pfunction ) ( const Object *o1, const Object *o2 )  = &SomeClass::getA;
Run Code Online (Sandbox Code Playgroud)

我想将此指针转换为静态模板函数指针:

template <class T>
static T ( *pfunction ) ( const Object <T> *, const Object <T> *); //Compile error
Run Code Online (Sandbox Code Playgroud)

哪里:

 class SomeClass
 {
  public:
    template <class T>
    static double getA ( const Object <T> *o1, const Object <T> *o2);
    ...
 };
Run Code Online (Sandbox Code Playgroud)

但是存在以下编译错误:

error: template declaration of : T (* pfunction )(const Object <T> *o1, const Object <T> *o2)
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助...

ice*_*ime 16

在第二种情况下,getA不再是函数而是函数模板,并且您不能拥有指向函数模板的指针.

你可以做的是pfunction指向一个特定的getA实例(即:for T = int):

class MyClass
{
    static double (*pfunction)(const Object<int> *, const Object<int> *);
};

double (*MyClass::pfunction)(const Object<int> *o1, const Object<int> *o2)  = &SomeClass::getA<int>;
Run Code Online (Sandbox Code Playgroud)

但我认为没有办法pfunction指出任何可能的实例getA.


And*_*hko 12

模板是一个模板 :)它不是具体的类型,不能用作成员.例如,您无法定义以下类:

class A
{
    template <class T> std::vector<T> member;
}
Run Code Online (Sandbox Code Playgroud)

因为template <class T> std::vector<T> member;它可能专门针对许多不同类型.你可以这样做:

template <class T>
struct A
{
 static T (*pfunction)();
};

struct B
{
 template <class T>
 static T getT();
};

int (*A<int>::pfunction)() = &B::getT<int>;
Run Code Online (Sandbox Code Playgroud)

A<int>是一个专门的模板,所以有专门的成员


Naw*_*waz 8

template <class T>
static T ( *pfunction ) ( const Object <T> *, const Object <T> *);
Run Code Online (Sandbox Code Playgroud)

函数指针模板在C++中是非法的.无论是在课堂上,还是仅仅在课堂之外.你不能写这个(甚至不在课外):

template <class X>
void (*PtrToFunction) (X);
Run Code Online (Sandbox Code Playgroud)

请参阅此示例:http://www.ideone.com/smh73

C++标准以14美元/ 1表示,

模板定义了一系列函数.

请注意,它没有说"模板定义了一系列,函数 或函数指针 ".所以你要做的是,使用模板定义"一系列函数指针",这是不允许的.

来自Loki库的Generic Functors 将是您遇到的问题的优雅解决方案.:-)