访问没有模板参数的嵌套模板形参
Accessing nested template parameters without template template arguments
我有这样的情况:
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; };
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- 创建具有嵌套环的 L 形图案
- 访问没有模板参数的嵌套模板形参
- 使用嵌套在模板形参中的typename