编译器在传递 const 变量时返回错误:模板参数不是常量表达式

Compiler returning an error when passing a const variable: template argument is not a constant expression

本文关键字:参数 表达式 常量 错误 const 变量 返回 编译器      更新时间:2023-10-16

所以我写了这段代码->

#include <iostream>
#include <bitset>
int main(){
int num, temp, digits = 0;
std::cin >> num;
temp = num;
while(temp){
temp /= 10;
++digits;
}
const int size = digits;
std::bitset<size> a(num);
std::cout << a << std::endl;
return 0;
}

位集容器不接受 const 整数大小作为参数并引发错误 -Non-type template argument is not a constant expression。我想知道为什么会发生这种情况,因为大小已被声明为常量,并且它的值在我的程序运行时不会改变?

>const变量可以有不同的解释,具体取决于分配给它的内容。

当分配编译时常量时
  1. :它将是一个编译时常量。这意味着在编译期间,常量值可以直接就地使用。

  2. 当从另一个变量(不是编译时常量(赋值时:新变量是不可修改的。从这个意义上说,变量不是编译时常量。它不能在该代码块中修改。

模板需要编译时常量。