Throw in constexpr function

clang is correct, note the HEAD revision of gcc accepts also accepts this code. This is a well-formed constexpr function, as long as there is value for the argument(s) that allows the function to be evaluated as a core constant expression. In your case 1 is such a value. This is covered in the draft … Read more

static_assert on initializer_list::size()

“Initializer lists” are just horrible kludges. Don’t: #include <initializer_list> template<typename T> void Dont(std::initializer_list<T> list) { // Bad! static_assert(list.size() == 3, “Exactly three elements are required.”); } void Test() { Dont({1,2,3}); } Do: template<typename T, std::size_t N> void Do(const T(&list)[N]) { // Good! static_assert(N == 3, “Exactly three elements are required.”); } void Test() { Do({1,2,3}); … Read more

C++ check if statement can be evaluated constexpr

Here’s another solution, which is more generic (applicable to any expression, without defining a separate template each time). This solution leverages that (1) lambda expressions can be constexpr as of C++17 (2) the type of a captureless lambda is default constructible as of C++20. The idea is, the overload that returns true is selected when … Read more

Difference between constexpr and static constexpr global variable

In your current example there is no difference: On variable declarations, constexpr implies const, and a const variable at namespace scope has internal linkage by default (so adding static does not change anything). In C++14, you cannot declare a variable as constexpr and have it have external linkage unless you only ever do this in … Read more

Is it possible to use std::string in a constant expression?

As of C++20, yes, but only if the std::string is destroyed by the end of constant evaluation. So while your example will still not compile, something like this will: constexpr std::size_t n = std::string(“hello, world”).size(); However, as of C++17, you can use string_view: constexpr std::string_view sv = “hello, world”; A string_view is a string-like object … Read more

Should I declare a constant instead of writing a constexpr function?

Suppose it does something a little more complicated. constexpr int MeaningOfLife ( int a, int b ) { return a * b; } const int meaningOfLife = MeaningOfLife( 6, 7 ); Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than just … Read more

constexpr exp, log, pow

Have you ever watch Sprout‘s implementaion? Sprout is header-only library that provide C++11/14 constexpr based Containers, Algorithms, Random numbers, Parsing, Ray tracing, Synthesizer, and others. https://github.com/bolero-MURAKAMI/Sprout/tree/master/sprout/math