访问没有模板参数的嵌套模板形参

Accessing nested template parameters without template template arguments

本文关键字:嵌套 形参 参数 访问      更新时间:2023-10-16

我有这样的情况:

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.
}

我希望能够使用User的模板参数的非类型参数来静态分配User类中的数据。我知道我可以使用模板模板参数在User中创建BaseWrapper<M>,但这不是我首选的方法。有什么简单的方法吗?

谢谢!

添加static const unsigned int Size = N;到您的类

的例子:

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

那么N在您的User类中可以作为T::Size访问。

方案1

将const静态成员数据声明为:

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

然后将此作为User类中的T::size:

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

解决方案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!
};

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

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];
};

最简单的方法是向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接受某种类型作为模板参数并提供N的值作为静态const成员,

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