天天看點

C++的騷操作(一)

使用者定義的字面量(user-defined literal)

  1. operator “” [suffix name], 舉例:operator “” _b8();
  2. 可用于普通函數,也可用于模闆函數
  3. 舉個例子,實作八進制的字面量,編譯時會計算出對應的整數值
// Example program
#include <iostream>
#include <string>

constexpr int ipow(int x, int n)
{
    return n > 0 ? x * ipow(x, n - 1) : 1;
}

template <char a>
constexpr int b8_helper()
{
    return a - '0';
}

template <char a, char b, char... tail>
constexpr int b8_helper()
{
    return (int)(a - '0') * ipow(8, sizeof...(tail) + 1) + b8_helper<b, tail...>();
}

template <char... digits>
constexpr int operator"" _b8()
{
    return b8_helper<digits...>();
}

int main()
{
    int a = 2121474_b8;
    std::cout << a << std::endl;
}
           
  1. 使用者隻能定義字面量字尾,而不能定義字首
  2. 對于非整數的字元串字面量,需要加上雙引号隔離字尾
  3. 使用者定義的字面量字尾最好以下劃線開頭,标準庫保留了所有不以下劃線開頭的字尾
  4. 對于普通函數,字面量的值會傳遞給參數;對于模闆,則會傳給模闆參數

繼續閱讀