我有一个模板:
template<unsigned int N> struct IntN;
template <> struct IntN< 8> {
typedef uint8_t type;
};
template <> struct IntN<16> {
typedef uint16_t type;
};
在 main 中,我通过这样做来初始化和交替:
IntN< 8>::type c;
这似乎有效,但是,当我将值存储在变量中时,它不起作用,并且出现以下错误:
error: non-type template argument of type 'int' is not an integral constant expression
代码示例如下:
template<unsigned int N> struct IntN;
template <> struct IntN< 8> {
typedef uint8_t type;
};
template <> struct IntN<16> {
typedef uint16_t type;
};
int main(int argc, char *argv[]) {
int foo = 8;
IntN<foo>::type c;
}
有人有什么想法吗?谢谢
最佳答案
整数模板参数的模板参数必须是常量表达式。整数文字是常量表达式
IntN<8>::type c;
用常量表达式初始化的常量变量是常量表达式
const int n = 8;
IntN<n>::type c;
这里 n 是可以的,因为它既是 const 又是由常量表达式 (8) 初始化的。以下将不会编译:
int n = 8;
const int m = n;
IntN<n>::type c; //error n is not const therefore not a constant expression
IntN<m>::type c; //error m is const but initialized with a non-constant expression therefore not a constant expression
关于c++ - 模板 - 传递变量而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14070969/