2

メンバー関数ポインター用のテンプレート ヘルパーを作成しようとしましたが、主なアイデアは次のようなことができるようにすることです。

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::pointerBad::pointerはどちらもタイプReturn (Type::*)(Parameter)なので、&A::Functionまたはを指すことができるはずStruct::Functionですが、明らかに間違っていますが、理由はわかりません。型がテンプレート化されたオブジェクト本体に宣言されているときと、テンプレート パラメーターとして宣言されているときでは、動作が異なるようです。

問題は、なぜorBad::pointerへの関数ポインタとして機能しないのです&A::Function&Struct::Function?

4

1 に答える 1

2

もしかして?

template <typename Type, 
          typename Return, 
          typename Parameter, 
          Return (Type::*Pointer)(Parameter)> struct Bad
{
    typedef Pointer pointer;
    //      ^^^^^^^ (not Parameter)
};
于 2012-11-21T15:07:01.467 に答える