【问题标题】:Compiler returning an error when passing a const variable: template argument is not a constant expression传递 const 变量时编译器返回错误:模板参数不是常量表达式
【发布时间】:2018-01-13 03:50:44
【问题描述】:

所以我写了这段代码->

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

【问题讨论】:

标签: c++ constants bitset std-bitset


【解决方案1】:

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

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

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

模板需要编译时间常数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多