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?
Best Answer
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: