15

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?

Xeo
  • 129,499
  • 52
  • 291
  • 397
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • 3
    I did not know about this template arguments thing. And it's super cool. – Quentin Jul 22 '14 at 10:07
  • 8
    Sorry, impossible unless we get `` UDL operators for string literals :( – Xeo Jul 22 '14 at 10:18
  • 2
    So much of the new standard seems incomplete and non-orthogonal. *sigh*. Maybe it'll be fixed in another 5-10 years. I guess it's better than the standard not shipping at all. – Mankarse Jul 22 '14 at 11:36
  • 1
    It really feels like an oversight on the part of the committee. The unicode string literals could translate into `template`, and `wchar_t` for wide strings – tclamb Jul 23 '14 at 18:39
  • 3
    We added it to g++ thinking it was going to make it into C++14. Sigh. It isn't standard but this compiles with -std=c++14 on g++-4.8 onwards. – emsr Jul 25 '14 at 04:12
  • 1
    Actually it works for -std=c++11. – emsr Jul 25 '14 at 04:14

1 Answers1

1

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524