非类型参数的模板参数必须是表达式 [英] Template argument for non-type parameter must be an expression
问题描述
为什么下面的代码错了?
Why is the following code wrong?
template <typename T, int N>
struct Vector {
T data[N];
};
struct Dynamic {
};
template <typename T>
struct Vector<T, Dynamic> {
T* data;
};
我尝试用 Vector< int,Dynamic> obj;
且无效
错误:非类型模板参数的模板参数必须是表达式
error: template argument for non-type template parameter must be an expression
为什么?我传递一个类型,我认为这是一个有效的模板专门化。
Why? I'm passing a type and I thought that was a valid template specialization.
如何使用两个模板,有一个请求N和一个,标记为动态
?
How can I use two templates and having one that requests N and one that doesn't if marked with Dynamic
?
推荐答案
template <typename T, int N>
struct Vector {
T data[N];
};
在您的主要模板类中, T
必须是类型,( int,short ,class-type等等
)... N
是一个非类型,并且必须是评估为 int
类型的表达式number)。
Here in your primary template class, T
must be a type, (int, short, class-type, etc
)... N
is a non-type, and must be an expression that evaluates to an int
type (a number).
struct Dynamic {
};
template <typename T>
struct Vector<T, Dynamic> {
T* data;
};
动态
是一种类型。不是您的主要模板中指定的 int
Dynamic
is a type. Not an int
as specified in your primary template
您的主模板类,您只能使用 int
专门化 Vector
的第二个模板参数。例如
Based on your primary template class, you can only specialize the second template parameter of Vector
with an int
. Eg.
template <typename T>
struct Vector<T, 1> {
T* data;
};
template <typename T>
struct Vector<T, 35> {
T* data;
};
template <typename T>
struct Vector<T, constExpressionThatReturnsAnInt> {
T* data;
};
...etc
这篇关于非类型参数的模板参数必须是表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!