C++ 模板-传递变量而不是值
我有一个模板:C++ 模板-传递变量而不是值,c++,templates,C++,Templates,我有一个模板: template<unsigned int N> struct IntN; template <> struct IntN< 8> { typedef uint8_t type; }; template <> struct IntN<16> { typedef uint16_t type; }; 基本上,我通过这样做来初始化和替换: IntN< 8>::type c; 这似乎是可行的,但
template<unsigned int N> struct IntN;
template <> struct IntN< 8> {
typedef uint8_t type;
};
template <> struct IntN<16> {
typedef uint16_t type;
};
基本上,我通过这样做来初始化和替换:
IntN< 8>::type c;
这似乎是可行的,但是,当我将值存储在变量中时,它不会起作用,并且我得到以下错误:
错误:“int”类型的非类型模板参数不是整型常量表达式
IntN<8>::type c;
const int n = 8;
IntN<n>::type c;
下面是一个代码示例:
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;
用常量表达式初始化的常量变量是常量表达式
IntN<8>::type c;
const int n = 8;
IntN<n>::type c;
这里n是确定的,因为它是常量,并且由常量表达式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
函数模板是一个蓝图,它告诉编译器在实例化函数时,即在代码中使用模板函数时,如何为函数生成代码
编译器将生成的具体内容取决于模板参数的实例化值。这些值必须在那时已知并最终确定,否则编译器不知道要生成什么代码。嘿,就是这样!但是我在程序的其他地方设置了这个值,因此它不能是常量。。有什么想法吗?@user1326876如果它的值是在运行时确定的,那么就无法将其作为模板参数传递。模板在编译时实例化