c++ - 模板 - 传递变量而不是值

标签 c++ templates

我有一个模板:

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/

相关文章:

c++ - 如何创建 QTableWidgetItem 右对齐的长文本,左侧有省略号?

c++ - 如何在 Eclipse 中启用 C++11 支持?

c++ - 对成员模板函数的访问控制

c++ - 将值传递给功能模板的最佳方法

c++ - QGraphicsItem 鼠标中键按下事件

c++ - 从另一个桌面捕获屏幕截图

c++ - View 类未接收更新的模型类数据

c++ - clang 6 和 clang 7 模板转换运算符区别

c++ - 是否可以根据约束 "overload"别名模板?

c++ - 抽象基类 C++ 中的静态回调