【问题标题】:Initializing with const array element用 const 数组元素初始化
【发布时间】:2015-01-28 18:33:06
【问题描述】:

为什么编译器(VC++)不允许(错误C2975)

const int HASH[] = {24593, 49157};
bitset<HASH[0]> k;

我能做些什么来克服这个问题(用数组中的常量值初始化模板)?

【问题讨论】:

  • 那么错误C2975 是什么?并非所有人都对 VC++ 编译器错误了如指掌。
  • 另外,请尝试使用constexpr 而不是const
  • msdn.microsoft.com/en-us/library/kyf0z2ka.aspx - 基本上它说常量表达式应该出现在尖括号内。
  • 这真的是你想做的吗,顺便说一句?也就是说,创建一个 24593 位的std::bitset&lt;N&gt;?您的意思是使用std::bitset&lt;std::numeric_limits&lt;int&gt;::digits&gt; k(HASH[0]); 也不会遇到您看到的问题吗?

标签: c++ arrays templates visual-c++ constants


【解决方案1】:

本地 const 对象不符合常量表达式的条件,但 std::bitset&lt;N&gt; 要求非类型模板参数 N 是常量表达式。带有初始值设定项的const 整数对象确实有资格作为常量表达式。在所有其他情况下,您将需要constexpr(我不知道MSVC++ 是否支持constexpr)。例如:

#include <bitset>

struct S { static int const member = 17; };
int const global_object = 17;
int const global_array[]  = { 17, 19 };
int constexpr global_constexpr_array[] = { 17, 19 };

int main()
{
    int const local = 17;
    int const array[] = { 17, 19 };
    int constexpr constexpr_array[] = { 17, 19 };

    std::bitset<S::member> b_member; // OK

    std::bitset<global_object>             b_global;                 // OK
    std::bitset<global_array[0]>           b_global_array;           // ERROR
    std::bitset<global_constexpr_array[0]> b_global_constexpr_array; // OK

    std::bitset<local>              b_local;           // OK
    std::bitset<array[0]>           b_array;           // ERROR
    std::bitset<constexpr_array[0]> b_constexpr_array; // OK
}

说了这么多,你确定你真的想要一个std::bitset&lt;N&gt; 和数组指定的元素数量吗?如果你真的对值的位感兴趣,你宁愿使用这样的东西:

std::bitset<std::numeric_limits<unsigned int>::digits> k(HASH[0]);

【讨论】:

  • 所以这在 VC++ 中是不可能的......哦,好吧。感谢您的回答! (是的,我确实想要 24593 位)
猜你喜欢
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 2014-08-08
  • 2012-09-01
相关资源
最近更新 更多