6. ◆constexpr とは?
• N3290
7.1.5 The constexpr specifier [dcl.constexpr]
1 The constexpr specifier shall be applied only to the definition of a variable,
the declaration of a function or function template, or the declaration of a
static data member of a literal type (3.9). If any declaration of a function or
function template has constexpr specifier, then all its declarations shall
contain the constexpr specifier. [ Note: An explicit specialization can differ
from the template declaration with respect to the constexpr specifier. -end
note ] [ Note: Function parameters cannot be declared constexpr.-end note ]
26. ◆条件分岐
• ⾮ constexpr 関数
template<class T>
T max(T const& a, T const& b) {
if (a < b) return b;
else return a;
}
if ⽂
↓
• constexpr 関数 条件演算⼦
template<class T>
constexpr T max(T const& a, T const& b) {
return (a < b) ? b : a;
}
27. ◆ループ
• ⾮ constexpr 関数
template<class Iter, class T>
Iter find(Iter first, Iter last, T const& val) {
while (first != last) {
if (*first == val) return first;
++first;
}
return first;
ループ構⽂
} ↓
再帰
• constexpr 関数
template<class Iter, class T>
constexpr Iter find(Iter first, Iter last, T const& val) {
return (first != last)
? (*first == val) ? first
: find(first + 1, last, val)
: first; ++演算⼦は使えない
} (副作⽤があるから)
28. ◆ループ
• ⾮ constexpr 関数
template<class Iter, class T>
Iter find(Iter first, Iter last, T const& val) {
while (first != last) {
if (*first == val) return first;
++first;
}
return first;
ループ構⽂
} ↓
再帰
• constexpr 関数
template<class Iter, class T>
constexpr Iter find(Iter first, Iter last, T const& val) {
return (first == last) || (*first == val) ? first
: find(first + 1, last, val);
} 式を整理して
このようにも書ける