【发布时间】:2016-11-20 17:47:38
【问题描述】:
我想将一个非常量变量转换为常量变量。我尝试使用 const_cast 但以下程序仍然给出错误,即“bitsize1”不能出现在常量表达式中。我做错了什么?
#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
int l = 3; // taken input from user
int bitsize2 = (l * 2);
int bitsize1 = const_cast<int&>(bitsize2);
string temp = "100101";
bitset<const_cast<int&>(bitsize2)> baz (temp);
cout << baz;
return 0;
}
【问题讨论】:
-
模板参数必须在编译时知道。
-
您对常量表达式和常量对象感到困惑。
const用于使对象不可修改,constexpr用于使值在编译时可用。
标签: c++ variables scope constants