Currently you cannot use static_assert
to verify parameters of a constexpr
function, even if all calls to it are indeed constexpr
.
That makes sense because the compiler still has to create a non-constexpr instantiation of this function in case some other module will try to call it.
Sadly, this is the case even if the function is static
or in an anonymous namespace.
C++20 however, will introduce a new keyword consteval
which is like constexpr
but it doesn't allow calling a function in a non-constexpr way. In this case, the compiler can know for sure that the function parameters will always be known at compile time. Therefore, in theory it should be possible to validate them with static_assert
.
The question is: Does the standard allow it?
Example:
#include <iostream>
consteval char operator""_bchar(const char text[], const size_t length)
{
static_assert(length == 8, "Binary char has to have 8 digits!"); // <-- This is currently not possible.
uint8_t byte = 0;
for (size_t i = 0; i != length; ++i)
{
byte <<= 1;
byte |= text[i] == '1' ? 0b00000001 : 0b00000000;
}
return byte;
}
int main()
{
std::cout << "01000001"_bchar << std::endl;
return 0;
}
I'm asking because I'm going to write some user-defined literals (more complicated than the example). I have an option to use compiler extensions to deal with the validation or wait a little for the compiler update and write fully standard-compliant code.
CONSTEVAL_STATIC_ASSERT
does not fail at compile-time. It throws the exception at run-time. I useg++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
. – Niccolo