c++ - 编译器在传递 const 变量 : template argument is not a constant expression 时返回错误

标签 c++ constants bitset std-bitset

所以我写了这段代码->

#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 变量可以有不同的解释,这取决于分配给它的内容。

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

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

模板需要一个编译时间常数。

关于c++ - 编译器在传递 const 变量 : template argument is not a constant expression 时返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45519811/

相关文章:

具有内置缓存的 C++ 对象工厂 - 阴影模板参数

math - 如何在 Visual C++ 2008 中访问数学常量(例如 M_PI)?

javascript - 将 React 计时器重置为初始常量值

c++ - 常量表达式参数

c++ - 将 cv::mat 加载到更快的 rcnn blob

c++ - 用于无等待生产者和阻塞消费者的环形缓冲区

c++ - 没有从 'Foo' 到 'Foo *const' C++ 的可行转换

java - 如何计算 BitSet 的大小(以字节为单位)?

java - 为什么 Java `BitSet` 没有 `shiftLeft` 和 `shiftRight` 函数?

c++ - 如何将库添加到eclipse中