编译器在传递 const 变量时返回错误:模板参数不是常量表达式
Compiler returning an error when passing a const variable: template argument is not a constant expression
所以我写了这段代码->
#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
变量可以有不同的解释,具体取决于分配给它的内容。
:它将是一个编译时常量。这意味着在编译期间,常量值可以直接就地使用。
当从另一个变量(不是编译时常量(赋值时:新变量是不可修改的。从这个意义上说,变量不是编译时常量。它不能在该代码块中修改。
模板需要编译时常量。
相关文章:
- 概念中的cv限定符需要表达式参数列表
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 使用自动推导的 lambda 参数作为常量表达式
- 编译器是否强制根据模板参数计算表达式?
- 错误:参数中无效地使用了无效表达式
- 将折叠表达式传递给可变参数模板
- 为什么带有指针子对象的文字类类型的 constexpr 表达式不能是非类型模板参数
- C++: priority_queue:模板参数中的 lambda 表达式
- 容器如何处理 lambda 表达式的参数
- 在C++ Lambda 表达式中,为什么人们更喜欢按值捕获而不是作为参数传递?
- 整体模板参数。错误:在常量表达式中使用'this'
- 我可以std::在fold表达式中转发参数吗
- 折叠表达式模板参数推导/替换失败
- 折叠表达式和参数包:static_assert 内 Args&& 和 Args 之间的区别
- C++:从捕获函数参数的函数返回 lambda 表达式
- 是否可以使用带有模板化参数的特征块表达式作为左值?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 如何在C++中将 lambda 表达式作为参数传递
- 导出模板参数表达式的类型