Monday, July 31, 2017

C++11: User-defined Literals: Four Kinds

There are four kinds of user-defined literals: Integer, Floating Point, String, and Char. Here are examples of each one.
#include &ltiostream&gt
int          operator""_type1 (unsigned long long   i               )
  {return 1  ;} // Integer Literal
double       operator""_type2a(long double          d               )
  {return 2.1;} // Floating-point Literal (Cooked)
double       operator""_type2b(const char         * s               )
  {return 2.2;} // Floating-point Literal (Raw)
const char * operator""_type3 (const char         * s, size_t length)
  {return s  ;} // String Literal
char         operator""_type4 (char                 c               )
 {return c  ;} // Character Literal

int main()
{
  std::cout << 5_type1       << " " 
            << 5.0_type2a    << " "
            << 5.0_type2b    << " " 
            << "Hello"_type3 << " "
            << 'c'_type4     << std::endl;
  return 0;
}
// Output: 1 2.1 2.2 Hello c
Reference: https://isocpp.org/wiki/faq/cpp11-language#udls

No comments:

Post a Comment