ใน C++11 ได้เพิ่มคุณสมบัติ User Defined Literals (UDL) เข้ามา ซึ่งช่วยให้เราสามารถสร้าง literal เองได้สำหรับ built-in types หรือ user-defined types นอกเหนือจาก literal มาตรฐานที่มีอยู่แล้ว
Built-in Literals ตัวอย่าง
31(Integer)3.5(Double)4.2F(Float)'p'(Character)31ULL(Unsigned Long Long)0xD0(Hexadecimal)"pq"(String)
ทำไมต้องใช้ UDL?
สมมติเราต้องการเก็บน้ำหนัก long double Weight = 3.5; แต่ไม่รู้หน่วย (กิโลกรัม? ปอนด์? กรัม?) ด้วย UDL เราสามารถผูกหน่วยกับค่าได้:
weight = 5.6kg; ratio = 5.6kg / 2.1lb;
UDL ช่วยให้โค้ดอ่านง่ายขึ้น และรองรับการแปลงหน่วยระหว่าง compile-time ลดค่าใช้จ่ายรันไทม์
ตัวอย่างการใช้งาน
#include <iostream>
#include <iomanip>
using namespace std;
unsigned long long int operator"" _kb(unsigned long long int x) {
return x * 1024;
}
unsigned long long int operator"" _b(unsigned long long int x) {
return x;
}
unsigned long long int operator"" _mb(unsigned long long int x) {
return x * 1024 * 1024;
}
int main() {
unsigned long long int size = 24_kb;
cout << "Size:" << size << endl;
cout << "Few more MB:" << (size + 2_mb) << endl;
cout << "Size Div:" << (10_kb / 2_kb) << endl;
cout << "1KB = " << (8_b * 128_b) << endl;
return 0;
}
เอาต์พุท
Size:24576 Few more MB:2121728 Size Div:5 1KB = 1024
สรุป
- UDL เริ่มต้นด้วย underscore
_ตามด้วยชื่อที่ต้องการ - รองรับ integer, floating-point, character, string literals
- ทำให้โค้ด expressive และ type-safe มากขึ้น