[英]C++, function pointer to the template function pointer
我有一个指向常见静态方法的指针
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)
谢谢你的帮助...
在第二种情况下, getA
不再是一个函数,而是一个函数模板 ,你不能有一个指向函数模板的指针。
您可以做的是将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
实例。
模板是一个模板 :)它不是具体的类型,不能用作成员。 例如,您无法定义以下类:
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>
是一个专门的模板,因此有专门的成员
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将是您遇到的问题的优雅解决方案。 :-)
你可以做的一件事是在cpp文件中有一个模板成员函数的副本,并指向那个ie
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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.