Can we not "normalize" the behavior of a constexpr function by using is_constant_evaluated ? I understand why the successful cases work, but can't wrap my head around why the unsuccessful one doesn't.
gcc12.2 with -std=c++20 flag
error: the value of ‘str1’ is not usable in a constant expression
constexpr auto numArgs = count(FMT); \
#include <memory>
#include <iostream>
#include <string.h>
template<size_t arrSize>
void print()
{
std::cout << "Number of format characters: " << arrSize << "\n";
}
constexpr size_t countFormat(const char* format)
{
if(format[0] == '\0')
return 0;
return (format[0] == '%' ? 1u : 0u) + countFormat(format + 1);
}
constexpr size_t count(const char* format)
{
return std::is_constant_evaluated() ? countFormat( format ) : 0;
}
#define LOGMSG(FMT) { \
constexpr auto numArgs = count(FMT); \
print<numArgs>(); \
}
int main()
{
const auto str1 = "Test %d %s";
constexpr auto str2 = "Test %d %s";
LOGMSG(str1);
LOGMSG(str2);
LOGMSG("Test %d %s");
return 0;
}
static const auto str1 = .... Then,str1should be known at compile time (in your code, it isn't, because it's a stack-based variable).LOGMSG(str1);, are you expectingstd::is_constant_evaluated()to betrueorfalse? Iftrue, then it's a problem thatstr1isn'tconstexpr. Iffalse, how can you possibly expect to save the results into aconstexprvariable?