メンバー関数ポインター用のテンプレート ヘルパーを作成しようとしましたが、主なアイデアは次のようなことができるようにすることです。
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;
それをしている間、ヘルパーなしでポインターを宣言する方が短いことに気づきました(これは今の問題ではありません;)が、理解できないエラーに駆り立てられました。ヘルパーの 2 つのバージョンがあるとします。
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;
};
1Good
つはメンバー関数型へのポインターを構造体本体に定義し、Bad
もう1つはそれをテンプレートパラメーターに定義してから構造体本体に定義しますtypedef
。
構造体を使用してGood
、テスト プログラムをコンパイルします。
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;
}
ただし、Bad
構造体を使用すると、コンパイル エラーが発生します。
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;
}
私の知る限り、Good::pointer
とBad::pointer
はどちらもタイプReturn (Type::*)(Parameter)
なので、&A::Function
またはを指すことができるはずStruct::Function
ですが、明らかに間違っていますが、理由はわかりません。型がテンプレート化されたオブジェクト本体に宣言されているときと、テンプレート パラメーターとして宣言されているときでは、動作が異なるようです。
問題は、なぜorBad::pointer
への関数ポインタとして機能しないのです&A::Function
か&Struct::Function
?