特殊なテンプレートクラスで非タイプのテンプレートパラメーターの値にアクセスすることは可能ですか?

StackOverflow https://stackoverflow.com/questions/1162401

質問

特殊なテンプレートクラスで非タイプのテンプレートパラメーターの値にアクセスすることは可能ですか?

専門化されたテンプレートクラスがある場合:

   template <int major, int minor> struct A {
       void f() { cout << major << endl; }
   }

   template <> struct A<4,0> {
       void f() { cout << ??? << endl; }
   }

上記のケースでは、変数を使用する代わりにハードコード値4と0が簡単であることがわかりますが、私が専門とするより大きなクラスがあり、値にアクセスできるようにしたいと思います。

<4,0>でアクセスすることは可能ですか majorminor 値(4および0)?または、定数としてテンプレートのインスタンス化に割り当てる必要がありますか?

   template <> struct A<4,0> {
       static const int major = 4;
       static const int minor = 0;
       ...
   }
役に立ちましたか?

解決

この種の問題は、「特性」構造の個別のセットを持つことで解決できます。

// A default Traits class has no information
template<class T> struct Traits
{
};

// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
    return Traits<T>();
}

template <int major, int minor> struct A 
{ 
    void f() 
    { 
        cout << major << endl; 
    }   
};

// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
    enum { major = N1, minor = N2 };
};

template <> struct A<4,0> 
{       
    void f() 
    { 
        cout << GetTraits(*this).major << endl; 
    }   
};

他のヒント

本当にあなたの質問に対する答えではありませんが、あなたはそれらを列挙することができます、つまり:

enum{
 specialisationMajor=4,
 specialisationMinor=0
};

template <> struct A<specialisationMajor,specialisationMinor> {
    static const int major = specialisationMajor;
    static const int minor = specialisationMinor;
    ...
}

本当にあなたの質問に対する答えではありませんが、以下のアイデアは私を一度助けました:

#include <iostream>

template <int major, int minor, int= major, int= minor> struct A {
    void f() { std::cout << major << '\n'; }
};

template <int major, int minor> struct A<major, minor, 4, 0> {
    void f() { std::cout << major << ':' << minor << '\n'; }
};

int main()
{
    A<3, 3>().f();
    A<4, 0>().f();
}

いいえ、特殊な非タイプテンプレートパラメーターにアクセスできません。しかし、ここにの実装で自分自身を繰り返さない方法があります f:

   template <int major, int minor>
   struct f_impl
   {
       void f() { cout << major << endl; }
   };

   template <int major, int minor>
   struct A : public f_impl<major, minor>
   {};

   template <> struct A<4,0> : public f_impl<4,0>
   {};

この例では、書く必要があるため、あまり得られません。 4,0 2回(だからあなたはそれを2回目に書くことができます cout あなたのopで)。ただし、テンプレートパラメーターを使用してより多くの関数がある場合、支払いを開始します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top