【问题标题】:Throwing with the ternary operator用三元运算符抛出
【发布时间】:2016-03-04 08:07:41
【问题描述】:

这样编译:

struct A{};
struct B{};

int main(){
  if(true)
    throw A();
  else
    throw B();  
}

,但是

struct A{};
struct B{};

int main(){
  throw( true ?  A() : B() );
}

不会。

我可以用三元运算符抛出吗?

【问题讨论】:

  • AB 是不同的类型,所以表达式 true ? A() : B() 是错误类型的(它必须是 A 或 B)。
  • 编译器错误应该指出AB 不兼容。 gcc 给error: incompatible operand types ('A' and 'B')
  • 这不是骗子;当throw 在三元运算符内时,被骗者指的是编译器崩溃,但这个问题却在外面(这是关于类型错误)。
  • @EdPlunkett 某人只是略过另一个问题,投票结束,意识到他们的错误,然后重新打开它。那个白痴。 ;-)
  • 你也不能std::cout << (true? 1 : "nope")。不足为奇。

标签: c++


【解决方案1】:

AB 是不同的、不兼容的类型,因此表达式 true ? A() : B() 是错误类型的(它必须是 AB)。

【讨论】:

    【解决方案2】:

    三元运算符需要在两条路径上具有相同的类型(或可转换为相同类型的东西),否则编译器无法推断类型安全。

    【讨论】:

      【解决方案3】:

      如果条件运算符有结果,则类型需要以某种方式兼容。如果类型不兼容,您仍然可以从三元运算符中抛出:

      condition? throw A(): throw B();
      

      虽然我尝试的所有编译器都编译了上述语句,但它似乎是非法的:根据 5.16 [expr.cond] 第 2 段,第一个项目符号“第二个或第三个操作数(但不是两者)是) 抛出表达式 (15.1); ..."。为了应对这种限制,可以使用类似

      的东西
      condition? (throw A()), true: throw B()
      

      【讨论】:

        猜你喜欢
        • 2019-11-12
        • 2013-07-20
        • 2011-12-18
        • 2016-01-08
        • 2012-09-02
        • 1970-01-01
        • 2023-03-24
        • 2015-07-16
        • 1970-01-01
        相关资源
        最近更新 更多