所以我写了这段代码->
#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;
}
bitset 容器不接受常量整数大小作为参数并抛出错误 -Non-type template argument is not a constant expression
。我想知道为什么会发生这种情况,因为大小已被声明为常量,并且它的值在我的程序运行时不会改变?
最佳答案
const
变量可以有不同的解释,这取决于分配给它的内容。
当分配一个编译时间常量时:它将是一个编译时间常量。这意味着在编译期间可以直接就地使用常量值。
当从另一个变量(不是编译时常量)赋值时:新变量是不可修改的。从这个意义上说,变量不是编译时常量。它不能在该代码块中修改。
模板需要一个编译时间常数。
关于c++ - 编译器在传递 const 变量 : template argument is not a constant expression 时返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45519811/