How wide-spread is this GNU extension on ternary operation?

对着背影说爱祢 提交于 2019-12-01 10:47:20

Some answers:

  1. GCC - yes
  2. MSVC - no (based on vanetto's answer)
  3. CLANG - no yes - the LLVM online compiler compiles it successfully.
  4. Intel C compiler - yes

Bottom line - not wide-spread. Only Intel's compiler, which is almost 100% gcc-compatible, supports this.?

C++11 workaround:

template<typename Fcond, typename Flast>
auto ternary2support(Fcond fcond, Flast flast) -> decltype(fcond())
{
  auto    cond_result= fcond();
  return  cond_result? cond_result : flast();
}


#define ternary2(c,case0) ternary2support(  [&](){ return (c);}, [&](){ return (case0);} )


void test_tern2()
{
  int i= 3;

  int res1= ternary2(--i,1000);
  int res2= ternary2(--i,1000);
  int res3= ternary2(--i,1000);

  std::cout<<" res1="<< res1<<" res2="<< res2<<" res3="<< res3;
  // output: res1=2 res2=1 res3=1000

}

int main(){test_tern2(); return 0;}

Lambda lasyness prevents the condition recalculation and unnecassary case0 expression evaluation (as the original ternary operator extension works)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!