Back to TILs

C++ string_literals

Date: 2023-04-06Last modified: 2023-12-22

Table of contents

Introduction

Add this line to get literals working without using namespace std statement;

using std::string_literals::operator""s;
#include <string>
#include <string_view>
#include <iostream>

using std::string_literals::operator""s;
using std::string_view_literals::operator""sv;

int main( [[maybe_unused]] int argc, [[maybe_unused]] char **argv )
{
  auto s = "my string"s;
  auto sv = "my string view"sv;

  std::cout << "The type of s is " << typeid(s).name() << std::endl;
  std::cout << "The type of sv is " << typeid(sv).name() << std::endl;
  return 0;
}

Possible output

The type of s is NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
The type of sv is St17basic_string_viewIcSt11char_traitsIcEE

References