C++自定义字面值

字符串字面值

c++支持各种类型的字符串。

std::string 字面值

c++ 11之后出了一个新特性,自定义字面值。std::string字面值就是在字符串后面加上s后缀,生成对应的c++字符串类实例,如下面所示:

using namespace std::string_literals;

int main() {
  std::string str{"hello"s};
  std::string str2{u8"Hello World"};
  std::wstring str3{L"hello"s};
  std::u16string str4{u"hello"s};
  std::u32string str5{U"hello"s};
  return 0;
}

自定义字面值

c++中有6种主要的字面值:整形、字符、浮点型、字符串、布尔、指针。c++ 11开始就可以基于6种基本的字面值去自定义自定义字面值。上面的s就是标准库为string自定义的字面值后缀,比如:std::string str = "hello"s + "World"s;

自定义字面值本质就是操作符重载,我们也可以自定义字面值。

struct Distance {
private:
  explicit Distance(long double val) : kilometers(val) {}

  friend Distance operator"" _km(long double val);
  friend Distance operator"" _mi(long double val);

  long double kilometers{0};

public:
  const static long double km_per_mile;
  long double get_kilometers() { return kilometers; }

  Distance operator+(Distance other) {
    return Distance(get_kilometers() + other.get_kilometers());
  }
};

const long double Distance::km_per_mile = 1.609344L;

Distance operator"" _km(long double val) { return Distance(val); }

Distance operator"" _mi(long double val) {
  return Distance(val * Distance::km_per_mile);
}

int main() {
  // construct using kilometers
  Distance d{402.0_km};
  std::cout << "Kilometers in d: " << d.get_kilometers() << std::endl;

  // construct using miles
  Distance d2{402.0_mi};
  std::cout << "Kilometers in d2: " << d2.get_kilometers() << std::endl;

  // add distances constructed with different units
  Distance d3 = 36.0_mi + 42.0_km;
  std::cout << "d3 value = " << d3.get_kilometers() << std::endl; // 99.9364
  return 0;
}

输出:
Kilometers in d: 402
Kilometers in d2: 646.956
d3 value = 99.9364

使用自定义字面值并没有什么性能上的优势或者劣势,只是代码看起来更有意义。

参考: