用户定义的文字定义

User defined literals definitions

我正在看 cppreference page for user defined 字面值,我想除了几个例子我什么都懂

template <char...> double operator "" _π(); // OK

这个运算符是如何工作的?你怎么称呼它?

double operator"" _Z(long double); // error: all names that begin with underscore
                                   // followed by uppercase letter are reserved
double operator""_Z(long double); // OK: even though _Z is reserved ""_Z is allowed

以上两个函数有什么区别?如果第一个函数没有错误,调用第一个函数与调用第二个函数有什么区别?

谢谢!

据我了解,这两个签名之间没有区别。

问题是标识符 _Z 在技术上由标准保留。主要区别在于有一个 space:

double operator""/*space*/_Z(long double); 

double operator""_Z(long double); 

删除 space 基本上是一种解决方法,理论上可以抑制错误(或更可能是警告)。

就您如何使用它们而言,您是否查看了您列出的 link 中的示例?

#include <iostream>

// used as conversion
constexpr long double operator"" _deg ( long double deg )
{
    return deg*3.141592/180;
}

// used with custom type
struct mytype
{
    mytype ( unsigned long long m):m(m){}
    unsigned long long m;
};
mytype operator"" _mytype ( unsigned long long n )
{
    return mytype(n);
}

// used for side-effects
void operator"" _print ( const char* str )
{
    std::cout << str;
}

int main(){
    double x = 90.0_deg;
    std::cout << std::fixed << x << '\n';
    mytype y = 123_mytype;
    std::cout << y.m << '\n';
    0x123ABC_print;
}

用户定义文字背后的想法是允许创建可应用于内置类型的运算符,该运算符可将内置文字转换为另一种类型。

编辑:

要调用这些运算符之一,您只需将运算符作为后缀附加到值文字。所以给出:

// used as conversion
constexpr long double operator"" _deg ( long double deg )
{
    return deg*3.141592/180;
}

调用代码可以是例如:

long double d = 45_deg;

至于使用 template <char...> double operator "" _π(); 也许看看 this.

template <char...> double operator "" _π(); // OK

How does this operator work? How can you call it?

1.234_π 会调用 operator "" _π<'1', '.', '2', '3', '4'>()。这种形式允许您检测通常无法检测到的拼写差异(例如 1.21.20),并允许您避免由于 1.2 无法准确表示而导致的舍入问题甚至 long double.

double operator"" _Z(long double); // error: all names that begin with underscore
                                   // followed by uppercase letter are reserved
double operator""_Z(long double); // OK: even though _Z is reserved ""_Z is allowed

What is the difference between the above two functions?

C++ 标准根据 tokens 定义语法,您可以将其解释为单词。 "" _Z 是两个标记,""_Z""_Z 是单个令牌。

这个区别很重要:给定 #define S " world!",然后是 "Hello" S,空格使 S 成为一个独立的标记,防止它被视为 user-defined文字后缀.

为了更容易编码,在定义这些函数时通常允许使用 "" _Z""_Z 语法,但是 "" _Z 语法要求 _Z 被视为标识符.当实现将 _Z 预定义为宏或将其声明为自定义关键字时,这可能会导致问题。