模板——传递变量而不是值

Templates - Passing variable instead of value

本文关键字:变量 模板      更新时间:2023-10-16

我有一个模板:

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;

这似乎可以工作,但是,当我将值存储在变量中时,它不起作用,我得到以下错误:

错误:'int'类型的非类型模板参数不是整型常量表达式

下面是一个示例代码:
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

函数模板是一个蓝图,它告诉编译器实例化时(即当你在代码中使用模板函数时)如何为函数生成代码。

确切地说,编译器将生成的取决于模板形参的实例化值。这些值必须已知并最终确定,否则编译器不知道生成什么代码。