Throw in constexpr function

后端 未结 2 919
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 12:25

The following piece of code compiles under clang++ 3.7.0 but is denied by g++ 5.3.1. Both have -std=c++14 option. Which compiler is correct? Anyone knows whe

2条回答
  •  天命终不由人
    2020-11-30 13:05

    As shown by Shafik Yaghmour it's a gcc bug, which is fixed in v6.1

    If you are still using the old gcc version you can revert to the c++11 constexpr style:

    constexpr auto foo(int n) -> int
    {
      return n <= 0 ? throw runtime_error("") : 1;
    }
    

    However there is a better workaround, still retaining all of the c++14 constexpr extensions:

    // or maybe name it
    // throw_if_zero_or_less
    constexpr auto foo_check_throw(int n) -> void
    {  
      n <= 0 ? throw std::runtime_error("") : 0;
    }
    
    constexpr auto foo(int n) -> int
    {
      foo_check_throw(n);
    
      // C++14 extensions for constexpr work:
      if (n % 2)
        return 1;
      return 2;
    }
    

提交回复
热议问题