Is it possible to define a user-defined string literal conversion operator such that the type of its result depends on the value of its string input?
It is easy with user-defined integer and floating point literals because they admit literal operator templates, and the actual characters of the literal are passed to it as template arguments. Example:
template <char... s> struct silly { using type = int; };
template <char... s> struct silly<'1', s...> { using type = double; };
template <char... s>
typename silly<s...>::type operator"" _silly() { return 0; }
static_assert(std::is_same<int, decltype(4321_silly)>::value, "no luck");
static_assert(std::is_same<double, decltype(1234_silly)>::value, "no luck");
No such thing seems to exist for user-defined string literals.
Is there perhaps another way to do this, either in the current standard or planned/discussed for some future revision?
No, not possible, outside of serious macro hackery. String literals are accessed via constexpr
, and return type of constexpr
cannot depend on values of arguments.
The proposed <char...>
operator""
for string literals ran into issues with "raw or processed" issues and how to specify it, and where dropped because hashing out those issues in time for the next standard would be hard, and/or ROI would be low. (at least from my casual reading of what happened).
I do not know if it died on the vine, or is still being worked on.
The hackery would be to pass <arr[0], arr[1], arr[2]>
to a template
pseduo-manually, and would not (directly) involve user defined literal syntax. It has many issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With