是否允许使用constexpr强制转换操作符在case标签中使用用户定义的对象

时间:2018-01-11 11:19:46

标签: c++ c++11 c++14 c++17

我正在尝试使用case构造函数和强制转换运算符在switch的{​​{1}}标签中使用用户定义的对象。这就是我想要的GCC和Clang,但如果没有MSVC的额外帮助就行不通。这让我想知道我正在尝试做的事情是否保证能够通过(任何版本)标准工作并且MSVC不合规(还),或者我很幸运,G ++和Clang以及MSVC被允许抱怨按标准。

我提出的最小例子如下:

constexpr

这导致我在GCC&铛:

#include <iostream>
#include <vector>

struct Foo
{
  int Value;

  constexpr Foo(int val)
  : Value (val)
  {
  }

  constexpr operator int() const
  {
    return Value;
  }
};

struct Bar
{
  static constexpr Foo Value = {42};
  constexpr operator int() const
  {
    return mValue;
  }

  constexpr Bar(int val)
  : mValue(val)
  {
  }
private:
  Foo mValue;
};

int main()
{
  std::vector<Bar> numbers = { 3, 42, 1 };
  for (auto i : numbers)
  {
    switch (i)
    //switch (static_cast<int>(i))  //<-- Adding the static_cast makes it work in MSVC as well
    {
      case 1:
        std::cout << "one" << std::endl;
        break;
      case Bar::Value:
        std::cout << "The answer to life, the universe and everything." << std::endl;
        break;
      default:
        std::cout << "Just a value: " << i << std::endl;
    };
  }
  return 0;
}

但在MSVC中导致以下错误:

Just a value: 3
The answer to life, the universe and everything.
one

在switch语句中添加source_file.cpp(46): error C2051: case expression not constant Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64 使MSVC也能理解它。因此,MSVC允许在案例标签中进行constexpr转换,但显然它不会将static_cast<int>转换为i。如果我正确理解(最新草案)标准,它应该将int转换为积分,但是它可能会选择与我提供转换的不同的积分类型?

我检查了GCC,Clang&amp;的行为。 MSVC通过http://rextester.com/ASWUZ96609

0 个答案:

没有答案
相关问题