【问题标题】:Pre-C++14 template metaprogramming and conditional operatorC++14 之前的模板元编程和条件运算符
【发布时间】:2018-03-12 12:38:39
【问题描述】:

来自cppreference.com

C++11 constexpr 中常用这种条件运算符 C++14 之前的编程。

std::string str = 2+2==4 ? "ok" : throw std::logic_error("2+2 != 4");

cppreference 指的是什么? C++14 之前的习语是什么?为什么在 C++14 中该技术不再相关?

【问题讨论】:

  • 在 C++14 之前,constexpr 函数只允许有一个语句 return,没有循环、没有分支等。这就是人们在return 语句来规避这个限制。

标签: c++ c++11 constexpr conditional-operator


【解决方案1】:

中,基本上在constexpr 函数中不能有多个语句。在 你可以。

constexpr bool str(int x){
  return  2+2==x ? true : throw std::logic_error("2+2 != x");
}

constexpr bool str(int x){
  if (2+2==x)
    return true;
  else
     throw std::logic_error("2+2 != x");
}

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2010-11-08
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多