10

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

専門のテンプレートクラスがある場合:

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

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

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

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

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

4 に答える 4

17

この種の問題は、「Traits」構造体の個別のセットを用意することで解決できます。

// 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; 
    }   
};
于 2009-07-22T03:19:47.827 に答える
1

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

enum{
 specialisationMajor=4,
 specialisationMinor=0
};

template <> struct A<specialisationMajor,specialisationMinor> {
    static const int major = specialisationMajor;
    static const int minor = specialisationMinor;
    ...
}
于 2009-07-22T00:17:40.213 に答える
0

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

#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();
}
于 2018-10-08T09:17:56.937 に答える
0

いいえ、特殊な非型テンプレートパラメータにアクセスすることはできません。しかし、ここに:の実装で自分自身を繰り返さない方法があります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,02回書き込む必要があるため、あまり多くを得ることができません(つまり、OPので2回も書き込むことができcoutます)。ただし、テンプレートパラメータを使用する関数がさらにある場合は、支払いが開始されます。

于 2019-09-10T21:09:30.753 に答える