Mar 9, 2014

[C++11] constexpr

constexpr definition
LiteralType definition

constexpr functions will be evaluated at compile time when :

  • all its arguments are constant expressions 
  • the result is used in a constant expression
A constant expression could be 
  • a literal (like 42), 
  • a non-type template argument (like N in template<class T, size_t N> class array;), 
  • an enum element declaration (like Blue in enum Color { Red, Blue, Green };
  • another variable declared constexpr.
They might be evaluated when all its arguments are constant expressions and the result is not used in a constant expression, but that is up to the implementation.


  • (§7.1.5/2): "constexpr functions and constexpr constructors are implicitly inline (7.1.2)."
  • constexpr member function can have declaration in the class and separate definition outside the class.
    • If any declaration of a function or function template has constexpr specifier, then all its declarations shall contain the constexpr specifier.
constexpr int get(bool b) { return b ? 42 : throw 111; } 

constexpr auto var1 = get(true); //OK 
constexpr auto var2 = get(false); //Ill-formed 
//--------------------------------------
enum class TreeColor { Red, Black, Exceptionary }; 

constexpr int decide(TreeColor c) { 
  switch (c) { 
  case TreeColor::Red: return 1; 
  case TreeColor::Black: return -1; 
  default: 
    throw invalid_args("Invalid TreeColor"); 
  } 
} 

virtual void foo() { 
  TreeColor c = ..; 
  int c = decide(c); // OK, may throw invalid_args 
} 

// OK, no throw expression evaluated 
constexpr int good_col = decide(TreeColor::Red); 
// Ill-formed, would evaluate throw expression 
constexpr int bad_col = decide(TreeColor::Exceptionary); 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.