4 ms·
This is even more C++11-ish: (Not tested, my compiler at work is not C++11 compliant.) constexpr tuple<double, double> Roots(double a, double b, double c)
by alexk7 15y ago
This is even more C++11-ish:
(Not tested, my compiler at work is not C++11 compliant.)
constexpr tuple<double, double> Roots(double a, double b, double c)
{
return (a == 0.0) ? throw invalid_argument("a has value 0.0!") :
tuple<double, double>{
(-b + (sqrt((b * b) - 4 * a * c))) / 2*a,
(-b - (sqrt((b * b) - 4 * a * c))) / 2*a
};
}
- jsnell 15y agoThat's just horrible. The readability of the function has been totally destroyed by conditional operator. What's the imaginary C++11-ish benefit?
- alexk7 15y agoWith constexpr, if the parameters are constants, the whole computation can happen at compile-time. The line is somewhat harder to read for people not used to functional programming, but unfortunately, constexpr functions are required to have a single expression.
- hythloday 15y agoIs return /* ... */ throw invalid_argument(""); really valid C++11?
- alexk7 15y ago"The rules for conditional operator are quite sophisticated and one of them says that if one of the sub-expressions is a throw expression, the type of the entire conditional operator is that of the other sub-expression." [1] [1] http://akrzemi1.wordpress.com/2011/05/06/compile-time-computations/ http://akrzemi1.wordpress.com/2011/05/06/compile-time-comput...
- hythloday 15y agoThanks for both your and pdw's explanations...the lovely thing about C++ is that there's always something new to learn. ;)
- pdw 15y agoIt's valid in all versions of C++, I believe. It's usually motivated with a chained ternary operator: return a == ALPHA ? x : a == BETA ? y : a == GAMMA ? z : throw ...; Although that's not a style I'd recommend.