何时以及如何使用模板文字运算符? [英] When and how to use a template literal operator?
问题描述
在 cppreference 上,有人提到可以使用模板用户文字运算符,但有一些限制:
On cppreference there is a mentioning that one can have templated user-literal operators, with some restrictions:
如果文字运算符是模板,则它必须具有一个空参数列表并且可以具有只有一个模板参数,该参数必须是元素类型为
char
的非类型模板参数包,例如
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?
}
问题:
- 该代码有效,但是如何将运算符与一些非空模板参数一起使用?
10_x<'a'> ;;
或10_<'a'&x;
不会编译。 li>
- 您是否有使用此类模板运算符的实际示例?
- 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?
推荐答案
10_x; // empty template list, how to specify non-empty template parameters?
那是不对的。模板参数列表不为空。
That isn't quite right. The template parameter list isn't empty. When you write:
template <char... Cs>
??? operator "" _x()
Cs
从文字左侧的内容中填充。也就是说,当您编写以下内容时:
The Cs
get populated from the stuff on the left-hand side of the literal. That is, when you write:
10_x
调用:
operator ""_x<'1', '0'>();
一个简单的例子是构建一个编译时,溢出安全的二进制文字,如下所示:
One simple example would be to build a compile time, overflow-safe binary literal such that:
template <uint64_t V>
constexpr uint64_t make_binary() {
return V;
}
template <uint64_t V, char C, char... Cs>
constexpr uint64_t make_binary() {
static_assert(C == '0' || C == '1', "invalid binary");
return make_binary<2*V + C - '0', Cs...>();
}
template <char... Cs>
uint64_t operator "" _b()
{
static_assert(sizeof...(Cs) <= 64, "overflow");
return make_binary<0, Cs...>();
}
uint64_t a = 101_b; // OK: a == 5
uint64_t b = 102_b; // error: invalid
uint64_t c = 11111111110000000000111111111100000000001111111111000000000011111111110000000000_b; // error: overflow
这篇关于何时以及如何使用模板文字运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!