[英]User defined literals definitions
我正在查看用戶定義的文字的cppreference頁面 ,我想除了幾個例子我理解了所有內容
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
上述兩個功能有什么區別? 如果第一個函數不是錯誤,那么調用第一個函數而不是第二個函數會有什么不同?
謝謝!
template <char...> double operator "" _π(); // OK
這個操作符如何工作? 你怎么稱呼它?
1.234_π
將調用operator "" _π<'1', '.', '2', '3', '4'>()
。 此表單允許您檢測通常無法檢測到的拼寫差異(例如, 1.2
vs 1.20
),並允許您避免因為1.2
甚至在long double
1.2
無法准確表示的舍入問題。
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
上述兩個功能有什么區別?
C ++標准根據標記定義語法,您可以將其解釋為單詞。 "" _Z
是兩個令牌, ""
和_Z
。 ""_Z
是一個單一的標記。
這種區別很重要:給定#define S " world!"
,然后是"Hello" S
,空格是使S
成為獨立標記的原因,使其無法被視為用戶定義的文字后綴。
為了便於編碼,在定義這些函數時通常允許使用"" _Z
和""_Z
語法,但"" _Z
語法要求將_Z
視為標識符。 當實現將_Z
預定義為宏或將其聲明為自定義關鍵字時,這可能會導致問題。
據我了解,這兩個標志之間沒有區別。
問題是標識符_Z
在技術上是由標准保留的。 主要區別在於有一個空間:
double operator""/*space*/_Z(long double);
double operator""_Z(long double);
刪除空間基本上是一種解決方法,理論上可以抑制錯誤(或更可能是警告)。
至於你如何使用它們,你看過你列出的鏈接中的例子嗎?
#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 "" _π();
也許看看這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.