我试图为成员函数指针创建一个模板助手,主要思想是能够做这样的事情:
template <typename T, typename R> struct TStruct
{
typedef T value_type;
typedef R return_type;
R Function(T &);
};
struct Struct
{
int Function(const int &);
};
typedef TStruct<const int &, int> A;
FunctionPointer<A, A::return_type, A::value_type>::pointer p = &A::Function;
typedef FunctionPointer<Struct, int, const int &>::pointer FPointer;
这样做时,我意识到在没有帮助器的情况下声明指针更短(现在这不是问题;)但它使我陷入了一个我不理解的错误。假设我们有两个版本的助手:
template <typename Type, typename Return, typename Parameter> struct Good
{
typedef Return (Type::*pointer)(Parameter);
};
template <typename Type, typename Return, typename Parameter, Return (Type::*Pointer)(Parameter)> struct Bad
{
typedef Parameter pointer;
};
一种将Good指向成员函数类型的指针定义到结构体中,Bad另一种将其定义到模板参数中,然后将typedef其定义到结构体中。
使用Goodstruct 我的测试程序编译:
int main(int argc, char **argv)
{
// No compilation errors
Good<A, A::return_type, A::value_type>::pointer GoodTStructPtr = &A::Function;
Good<Struct, int, const int &>::pointer GoodStructPtr = &Struct::Function;
return 0;
}
但是如果使用Badstruct,就会出现编译错误:
int main(int argc, char **argv)
{
// invalid initialization of reference of type ‘const int&’
// from expression of type ‘int (TStruct<const int&, int>::*)(const int&)’
Bad<A, A::return_type, A::value_type, &A::Function>::pointer BadTStructPtr = &A::Function;
// invalid initialization of reference of type ‘const int&’
// from expression of type ‘int (Struct::*)(const int&)’
Bad<Struct, int, const int &, &Struct::Function>::pointer BadStructPtr = &Struct::Function;
return 0;
}
AFAIK,Good::pointer并且Bad::pointer都是这种类型Return (Type::*)(Parameter),因此它们必须能够指向&A::Functionor Struct::Function,但我显然错了,但我不知道为什么。在将类型声明为模板化对象主体以及将其声明为模板参数时,似乎存在不同的行为。
所以问题是:为什么不能使用指向or的Bad::pointeras 函数指针&A::Function&Struct::Function?