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

时间:2011-01-01 11:43:24

标签: c++ templates function-pointers

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

class MyClass
{
  private:
    static double ( *pfunction ) ( const Object *, const Object *);
    ...
};

指向静态方法

 class SomeClass
 {
  public:
    static double getA ( const Object *o1, const Object *o2);
    ...
 };

初​​始化:

double ( *MyClass::pfunction ) ( const Object *o1, const Object *o2 )  = &SomeClass::getA;

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

template <class T>
static T ( *pfunction ) ( const Object <T> *, const Object <T> *); //Compile error

其中:

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

但是存在以下编译错误:

error: template declaration of : T (* pfunction )(const Object <T> *o1, const Object <T> *o2)

感谢您的帮助......

4 个答案:

答案 0 :(得分:15)

在第二种情况下,getA不再是一个函数,而是一个函数 template ,并且你不能有一个指向函数模板的指针。

您可以做的是pfunction指向特定getA实例(即: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>;

但我认为没有办法让pfunction指向任何可能的getA实例。

答案 1 :(得分:12)

模板是模板 :)它不是具体类型,不能用作成员。例如你不能定义以下类:

class A
{
    template <class T> std::vector<T> member;
}

因为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>;

此处A<int>是一个专门的模板,因此有专门的成员

答案 2 :(得分:8)

template <class T>
static T ( *pfunction ) ( const Object <T> *, const Object <T> *);

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

template <class X>
void (*PtrToFunction) (X);

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

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

  

模板定义了一系列   或功能

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

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

答案 3 :(得分:2)

你可以做的一件事是在cpp文件中有一个模板成员函数的副本并指向那个

template <+typename ElementType>
int PQueueHeap<ElementType>::compareFunction(ElementType First,ElementType Second)
{   
    if (First>Second) return 1; else if (First==Second) return 0; else return -1;
}

// you cannot point to above 

然而你可以指向

template <+typename ElementType>

int compareFunction(ElementType First,ElementType Second)
{

if (First>Second) return 1; else if (First==Second) return 0; else return -1;
} // No error and it works! 
相关问题