I'm writing a constexpr
code and I would like to inspect computed values at compile time.
The usual trick is to do something like this:
struct ReturnValue
{
int value1;
int value2;
};
constexpr ReturnValue doTheComputation()
{
return { .value1 = 10, .value2 = 20 };
}
template< auto t > struct p;
p< doTheComputation() > foo;
This gives a nice compile error:
implicit instantiation of undefined template 'p<ReturnValue{10, 20}>'
and I can see the value of the result.
However, this does not work for non-structural types, like std::string_view
, std::string
, or anything that resembles a string, as such types are not allowed to be NTTP.
Non-working example with std::string_view
: https://godbolt.org/z/da8W557nK
Non-working example with char const *
: https://godbolt.org/z/5Mvqfx95q
Even if I use char const[ some_large_numer ]
to ensure the message fits, like this, instead of a string, I get the ASCII values listed as template parameters:
implicit instantiation of undefined template 'p<ReturnValue{{115, 111, 109, 101, 32, 115, 101, 99, 114, 101, ...}}>
Are there any tips or tricks to print values of non-structural types at compile-time (as results of constexpr functions)?
I've seen an unofficial patch for GCC that apparently solves that (I haven't tested it), but I'm searching for a solution for clang (Apple-clang from Xcode 15 or newer and LLVM 18 or newer).
return {.value1 = 10, .value2 = 20}
to justreturn {10,20}
– Stasnyp<std::format("{}", doTheComputation())>
. – Crewsizeof()
oroffsetof
. – Breakablestd::format
does not work for the same reason I mentioned in the original question -std::format
returnsstd::string
, which is not structural type, hence cannot be used as a NTTP. – Rima{10, 20}
is considered a bad practice as it's ambiguous. – Rimavalue1
is declared beforevalue2
and this is the only way they will be initialized in{10, 20}
. There's no ambiguity about it whatsoever. It may be helpful/useful but not because it removes any ambiguity. – StasnyReturnValue
is far away (for example in another file). I prefer being explicit. – Crewreturn Rectangle{.width=3, .height=4};
is clearer thanreturn Rectangle{3,4}
for someone that reads the code. I'm not talking about writing it. – Crew