Sometimes it is convenient or even necessary to have a function which just one statement (it is necessary when returning a constexpr
). If a condition needs to be checked and only one statement is allowed, the conditional operator is the only option. In case of an error it would be nice to throw an exception from the conditional operator, e.g.:
template <typename It>
typename std::iterator_traits<It>::reference
access(It it, It end) {
return it == end? throw std::runtime_error("no element"): *it;
}
The above function doesn't compile, however, when used for example as (live example):
std::vector<int> v;
access(v.begin(), v.end());
The compiler complains about trying to bind a non-const
reference to a temporary. The compiler doesn't complain about the throw
-expression per se, though. So the question: Can exceptions be thrown from the conditional operator and, if so, what's going wrong with the above code?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…