2011-11-10 90 views
2

我有这种情况:访问嵌套模板参数

template<unsigned int N> 
class Base 
{ 
public: 
    Base(){} 
    int myint[N]; 
}; 

template<unsigned int M> 
class BaseWrapper : Base<M> 
{ 
public: 
    BaseWrapper(){} 
}; 

template<typename T> 
class User 
{ 
public: 
    User(){} 
    //int myint[T::N]; //How to statically allocate using M or N from above? 
}; 

int main(void) 
{ 
    User<BaseWrapper<10> > myuser; 
    // Do something with User::myint here. 
} 

我希望能够使用模板参数的非类型参数UserUser类静态分配数据。我知道我可以使用模板模板参数在User内部创建BaseWrapper<M>,但这不是我的首选方法。任何简单的方法来做到这一点?

谢谢!

回答

3

static const unsigned int Size = N;添加到您的班级。

例子:

template<unsigned int N> 
class Base 
{ 
public: 
    Base(){} 
    int myint[N]; 
    static const unsigned int Size = N; 
}; 

然后N是你在UserT::Size访问。

2

溶液1

声明一个常量静态成员数据为:

template<typename T> 
class User 
{ 
public: 
    User(){} 
    int myint[T::size]; //you can do this! 
}; 

所以:

template<unsigned int M> 
class BaseWrapper : Base<M> 
{ 
public: 
    static const unsigned int size = M; //add this line! 
    BaseWrapper(){} 
}; 

User类然后使用这个作为T::size lution 2

或者,如果你不能添加size作为成员(无论何种原因),那么你可以使用这种方法为:

template<typename T> struct get; 

template<unsigned int N> 
struct get< BaseWrapper<N> > //partial specialization! 
{ 
    static const unsigned int size = N; 
}; 


template<typename T> 
class User 
{ 
public: 
    User(){} 
    int myint[get<T>::size]; //get the size! 
}; 
0

可以公开模板参数作为类的静态成员变量:

template<unsigned int M> 
class BaseWrapper : Base<M> 
{ 
public: 
    static const int counter = M; 
    BaseWrapper(){} 
}; 

然后你就可以在你的User类使用静态成员:

template<typename T> 
class User 
{ 
public: 
    User(){} 
    int myint[T::counter]; 
}; 
0

其他人已经提到的最简单的方法是将一个静态成员添加到Basewrapper,该成员初始化为N

但是,如果由于某种原因,你不能改变User,还有一个办法让在N:

template<typename T> struct get_N; 
template<unsigned int N> struct get_N<Basewrapper<N> > { unsigned int const value = N; }; 

现在您的User模板你只可以写get_N<T>::value。这

一个优点是可以适应在事后的任何类型的不接触它的定义,所以如果你想在别的比Basewrapper实例User,说上Newbasewrapper,你只需要添加行

template<unsigned int N> struct get_N<Newbasewrapper<N> > { unsigned int const value = N; }; 

,或者如果Newbasewrapper需要一些类型作为模板参数,并且提供静态const成员的N的值,

template<typename T> struct get_N<Basewrapper<T> > { unsigned int const value = Basewrapper<T>::N; };