C++, function pointer to the template function pointer

徘徊边缘 提交于 2019-11-28 06:23:49

In the second case, getA is not a function anymore but a function template, and you can't have a pointer to function template.

What you can do is have pfunction point to a particular getA instance (ie: 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>;

But I don't think there is a way to get pfunction to point on any possible instance of getA.

template is a template :) it's not a concrete type and cannot be used as a member. e.g. you cannot define following class:

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

because template <class T> std::vector<T> member; is something that potentially can be specialized to many different types. you can do something like this:

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

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

int (*A<int>::pfunction)() = &B::getT<int>;

here A<int> is a specialized template and so has specialized member

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

Template of function pointer is illegal in C++. Be it inside a class, or simply outside a class. You cannot write this (not even outside a class):

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

See this sample : http://www.ideone.com/smh73

The C++ Standard says in $14/1,

A template defines a family of classes or functions.

Please note that it does NOT say "A template defines a family of classes, functions or function pointers". So what you're trying to do is, defining "a family of function pointers" using template, which isn't allowed.

Generic Functors from Loki library would be an elegant solution to the kind of problem you're having. :-)

Adel

One thing you can do is have a copy of the template member function in the cpp file and point to that i.e.

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 

however you can point to

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! 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!