Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal with dependent type — impossible?

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?

like image 786
n. 1.8e9-where's-my-share m. Avatar asked Jul 22 '14 09:07

n. 1.8e9-where's-my-share m.


1 Answers

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.

like image 182
Yakk - Adam Nevraumont Avatar answered Oct 21 '22 05:10

Yakk - Adam Nevraumont