C++ 在没有模板参数的情况下访问嵌套模板参数
我有这样的情况:C++ 在没有模板参数的情况下访问嵌套模板参数,c++,templates,nested,C++,Templates,Nested,我有这样的情况: 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: Use
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.
}
我希望能够使用模板参数的non-type参数对用户静态分配用户类中的数据。我知道我可以使用模板参数在用户内部创建BaseWrapper,但这不是我的首选方法。有什么简单的方法可以做到这一点吗
谢谢 添加静态常量unsigned int Size=N;为你们班干杯
例如:
template<unsigned int N>
class Base
{
public:
Base(){}
int myint[N];
static const unsigned int Size = N;
};
然后N在用户类中可以作为T::Size访问。解决方案1
将常量静态成员数据声明为:
template<unsigned int M>
class BaseWrapper : Base<M>
{
public:
static const unsigned int size = M; //add this line!
BaseWrapper(){}
};
解决方案2
或者,如果出于任何原因无法将大小添加为成员,则可以使用以下方法:
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!
};
可以将模板参数作为类的静态成员变量公开:
template<unsigned int M>
class BaseWrapper : Base<M>
{
public:
static const int counter = M;
BaseWrapper(){}
};
其他人已经提到过的最简单的方法是向Basewrapper添加一个静态成员,该成员被初始化为N 但是,如果出于某种原因您无法更改用户,还有一种方法可以获得N:
template<typename T> struct get_N;
template<unsigned int N> struct get_N<Basewrapper<N> > { unsigned int const value = N; };
或者,如果Newbasewrapper将某个类型作为模板参数,并将N的值作为静态常量成员提供
template<typename T> struct get_N<Basewrapper<T> > { unsigned int const value = Basewrapper<T>::N; };
template<typename T> struct get_N;
template<unsigned int N> struct get_N<Basewrapper<N> > { unsigned int const value = N; };
template<unsigned int N> struct get_N<Newbasewrapper<N> > { unsigned int const value = N; };
template<typename T> struct get_N<Basewrapper<T> > { unsigned int const value = Basewrapper<T>::N; };