【问题标题】:C++: casting non constant to constantC ++:将非常量转换为常量
【发布时间】: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


【解决方案1】:

const_cast 用于强制转换 const 而不是使某些东西成为 const。如果你想要常量表达式,在后 C++11 编程中最简单的方法是使用 constexpr:

constexpr int l = 3;
constexpr int bitsize2 = l * 2;

来自用户的输入不能是编译时常量表达式,因此您必须找出其他内容。

【讨论】:

  • const_cast 可用于删除或添加 const。在某些情况下可以隐式添加const,但也有需要const_cast 的情况。不过,您是对的,它不会将运行时值转换为编译时常量。
  • 有趣;我会在未来记住这一点。我从来不需要反过来做。感谢您的提醒。
【解决方案2】:

模板在编译时扩展,这意味着编译时应该知道所有模板参数。显然,用户输入是运行时数据,因此不能用作模板参数。

【讨论】:

    【解决方案3】:

    正如其他人所说,您无法在运行时推断模板参数。
    您应该考虑使用 boost 的 dynamic bitset
    它存在于您遇到的确切问题。

    “dynamic_bitset 类与 std::bitset 类几乎相同。 不同之处在于dynamic_bitset的大小( 位)在运行时指定 dynamic_bitset 对象,而 std::bitset 的大小是指定的 在编译时通过一个整数模板参数。"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多