On cppreference there is a mentioning that one can have templated user-literal operators, with some restrictions:
If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a non-type template parameter pack with element type
char
, such as
template <char...> double operator "" _x();
So I wrote one like in the code below:
template <char...>
double operator "" _x()
{
return .42;
}
int main()
{
10_x; // empty template list, how to specify non-empty template parameters?
}
Question:
- The code works, but how can I use the operator with some non-empty template parameters?
10_x<'a'>;
or10_<'a'>x;
does not compile. - Do you have any example of real-world usage of such templated operators?
That isn't quite right. The template parameter list isn't empty. When you write:
The
Cs
get populated from the stuff on the left-hand side of the literal. That is, when you write:that calls:
One simple example would be to build a compile time, overflow-safe binary literal such that:
Your template parameters are already specified--they're the source-code characters comprising your literal value! So for
10_x
, you're actually calling:Here's a working example. It compiles without error, and none of the assertions are triggered.
You can elaborate the parameters pack somehow (as mentioned by others) or access them as a compile-time string if you prefer:
You can use the above mentioned technique to deal with compile-time string-to-num converter and have something like
10_x
instead off("10")
or whatever.