簡體   English   中英

如何在模板化類型上專門化模板類的靜態成員?

[英]How do I specialize a static member of a template class on a templated type?

說我有以下課程:

template<class T>
struct A
{
    static int value;
};

template<class T>
int A<T>::value = 0;

我可以在具體類型上專門化A::value而不會出現問題:

struct B
{
};

template<>
int A<B>::value = 1;

我想在模板類型上專門化A ::值,我嘗試了以下方法:

template<class T>
struct C
{
};

// error: template definition of non-template 'int A<C<T> >::value'
template<>
template<class T>
int A<C<T> >::value = 2;

有沒有辦法做到這一點,或者只能在非模板類型上專門化A ::值?

您可以專門初始化,而不是引入完整的顯式特化

template<class T>
struct Value {
  static int const value = 0;
};

template<class T>
struct Value< C<T> > {
  static int const value = 2;
};

template<class T>
int A<T>::value = Value<T>::value;

您可以通過C使用A的部分特化:

#include <iostream>

using namespace std;

template<class T>
struct A
{
    static int value;
};

template<class T>
int A<T>::value = 0;

//(1) define the C template class first:
template<class T>
struct C
{
};

//(2) then define the partial specialization of A, in terms of C:
template<typename T>
struct A<C<T> > 
{
    static int value;
};

template<typename T>
int A<C<T> >::value = 2;

int main(void)
{
    cout<<A<C<int> >::value<<endl;

    cout<<"ok!"<<endl;
    return 0;
}

通過模板模板參數進行部分特化(參見上面的評論):

#include <iostream>

using namespace std;

template<class T>
struct A
{
    static int value;
};

template<class T>
int A<T>::value = 0;



//solution 2:
//define a template-template argument partial specialization
//for any generic class U depending on a template argument,
//(which is a typename, in this case, but there's no reason why
//you wouldn't define specializations for non-types, etc.)
//this specialization has the advantage of not depending on
//the template definition of U (or C, etc.); in this case
//both T and U are free to vary, with the only constraint
//that U is parameterized by T:
template<typename T, template<typename> class U>
struct A<U<T> >
{
    static int value;
};

template<typename T, template<typename> class U>
int A<U<T> >::value = 3;

//define the C template class, somewhere, where/when/if needed
//possibly in a different namespace, "module" (etc.)
template<class T>
struct C
{
};

int main(void)
{
    cout<<A<C<int> >::value<<endl;//this now should print out: 3

    cout<<"ok!"<<endl;
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM