Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      User-defined literals(since C++11)

      From cppreference.com
      <cpp‎ |language
       
       
      C++ language
      General topics
      Flow control
      Conditional execution statements
      Iteration statements (loops)
      Jump statements
      Functions
      Function declaration
      Lambda function expression
      inline specifier
      Dynamic exception specifications(until C++17*)
      noexcept specifier(C++11)
      Exceptions
      Namespaces
      Types
      Specifiers
      constexpr(C++11)
      consteval(C++20)
      constinit(C++20)
      Storage duration specifiers
      Initialization
      Expressions
      Alternative representations
      Literals
      Boolean -Integer -Floating-point
      Character -String -nullptr(C++11)
      User-defined(C++11)
      Utilities
      Attributes(C++11)
      Types
      typedef declaration
      Type alias declaration(C++11)
      Casts
      Memory allocation
      Classes
      Class-specific function properties
      Special member functions
      Templates
      Miscellaneous
       
      Expressions
      General
      Literals
      Escape sequences
      String literals
      Null pointer literal(C++11)
      User-defined literal(C++11)
      Operators
      Conversions
       

      Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix.

      Contents

      [edit]Syntax

      A user-defined literal is an expression of any of the following forms

      decimal-literalud-suffix (1)
      octal-literalud-suffix (2)
      hex-literalud-suffix (3)
      binary-literalud-suffix (4)
      fractional-constantexponent-part (optional)ud-suffix (5)
      digit-sequenceexponent-partud-suffix (6)
      character-literalud-suffix (7)
      string-literalud-suffix (8)
      1-4) user-defined integer literals, such as12_km
      5-6) user-defined floating-point literals, such as0.5_Pa
      7) user-defined character literal, such as'c'_X
      8) user-defined string literal, such as"abd"_L oru"xyz"_M
      decimal-literal - same as ininteger literal, a non-zero decimal digit followed by zero or more decimal digits
      octal-literal - same as ininteger literal, a zero followed by zero or more octal digits
      hex-literal - same as ininteger literal,0x or0X followed by one or more hexadecimal digits
      binary-literal - same as ininteger literal,0b or0B followed by one or more binary digits
      digit-sequence - same as infloating literal, a sequence of decimal digits
      fractional-constant - same as infloating literal, either adigit-sequence followed by a dot (123.) or an optionaldigit-sequence followed by a dot and anotherdigit-sequence (1.0 or.12)
      exponent-part - same as infloating literal, the lettere or the letterE followed by optional sign, followed bydigit-sequence
      character-literal - same as incharacter literal
      string-literal - same as instring literal, including raw string literals
      ud-suffix - an identifier, introduced by aliteral operator or aliteral operator template declaration (seebelow)

      In theinteger andfloating-point digit sequences, optional separators' are allowed between any two digits.

      (since C++14)

      If a token matches a user-defined literal syntax and a regular literal syntax, it is assumed to be a regular literal (that is, it's impossible to overloadLL in123LL).

      When the compiler encounters a user-defined literal withud-suffixX, it performsunqualified name lookup, looking for a function with the nameoperator""X. If the lookup does not find a declaration, the program is ill-formed. Otherwise,

      1) For user-defined integer literals,
      a) if the overload set includes a literal operator with the parameter typeunsignedlonglong, the user-defined literal expression is treated as a function calloperator""X(n ULL), wheren is the literal withoutud-suffix;
      b) otherwise, the overload set must include either, but not both, a raw literal operator or a numeric literal operator template. If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function calloperator""X("n ");
      c) otherwise, if the overload set includes a numeric literal operator template, the user-defined literal expression is treated as a function calloperator""X<'c1 ','c2 ','c3 '...,'ck '>(), wherec1..ck are the individual characters ofn and all of them are from thebasic character set.
      2) For user-defined floating-point literals,
      a) If the overload set includes a literal operator with the parameter typelongdouble, the user-defined literal expression is treated as a function calloperator""X(f  L), wheref is the literal withoutud-suffix;
      b) otherwise, the overload set must include either, but not both, a raw literal operator or a numeric literal operator template. If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function calloperator""X("f  ");
      c) otherwise, if the overload set includes a numeric literal operator template, the user-defined literal expression is treated as a function calloperator""X<'c1 ','c2 ','c3 '...,'ck '>(), wherec1..ck are the individual characters off and all of them are from thebasic character set.
      3) For user-defined string literals, letstr be the literal withoutud-suffix:
      a) If the overload set includes a string literal operator template with a constant template parameter for whichstr is a well-formed template argument, then the user-defined literal expression is treated as a function calloperator""X<str>();
      (since C++20)
      b) otherwise, the user-defined literal expression is treated as a function calloperator""X(str, len), wherelen is the length of the string literal, excluding the terminating null character.
      4) For user-defined character literals, the user-defined literal expression is treated as a function calloperator""X(ch), wherech is the literal withoutud-suffix.
      longdouble operator""_w(longdouble);std::string operator""_w(constchar16_t*, size_t);unsigned    operator""_w(constchar*); int main(){1.2_w;// calls operator ""_w(1.2L)    u"one"_w;// calls operator ""_w(u"one", 3)12_w;// calls operator ""_w("12")"two"_w;// error: no applicable literal operator}

      When string literal concatenation takes place intranslation phase 6, user-defined string literals are concatenated as well, and theirud-suffixes are ignored for the purpose of concatenation, except that only one suffix may appear on all concatenated literals:

      int main(){    L"A""B""C"_x;// OK: same as L"ABC"_x"P"_x"Q""R"_y;// error: two different ud-suffixes (_x and _y)}

      [edit]Literal operators

      The function called by a user-defined literal is known asliteral operator (or, if it's a template,literal operator template). It is declared just like any otherfunction orfunction template at namespace scope (it may also be a friend function, an explicit instantiation or specialization of a function template, or introduced by a using-declaration), except for the following restrictions:

      The name of this function can have one of the two forms:

      operator ""identifier (1)(deprecated)
      operatoruser-defined-string-literal (2)
      identifier - theidentifier to use as theud-suffix for the user-defined literals that will call this function
      user-defined-string-literal - the character sequence"" followed, without a space, by the character sequence that becomes theud-suffix
      1) Declares a literal operator.
      2) Declares a literal operator. This syntax makes it possible to use language keywords andreserved identifiers asud-suffix es, for example,operator""if from the header<complex>.

      ud-suffix must begin with the underscore_: the suffixes that do not begin with the underscore are reserved for the literal operators provided by the standard library. It cannot contain double underscores__ as well: such suffixes are also reserved.

      If the literal operator is a template, it must have an empty parameter list and can have only one template parameter, which must be a constant template parameter pack with element typechar (in which case it is known as anumeric literal operator template):

      template<char...>double operator""_x();

      or a constant template parameter of class type (in which case it is known as astring literal operator template):

      struct A{constexpr A(constchar*);}; template<A a>A operator""_a();
      (since C++20)

      Only the following parameter lists are allowed on literal operators:

      (constchar*) (1)
      (unsignedlonglongint) (2)
      (longdouble) (3)
      (char) (4)
      (wchar_t) (5)
      (char8_t) (6)(since C++20)
      (char16_t) (7)
      (char32_t) (8)
      (constchar*,std::size_t) (9)
      (constwchar_t*,std::size_t) (10)
      (const char8_t*,std::size_t) (11)(since C++20)
      (constchar16_t*,std::size_t) (12)
      (constchar32_t*,std::size_t) (13)
      1) Literal operators with this parameter list are theraw literal operators, used as fallbacks for integer and floating-point user-defined literals (see above)
      2) Literal operators with these parameter lists are the first-choice literal operator for user-defined integer literals
      3) Literal operators with these parameter lists are the first-choice literal operator for user-defined floating-point literals
      4-8) Literal operators with these parameter lists are called by user-defined character literals
      9-13) Literal operators with these parameter lists are called by user-defined string literals

      Default arguments are not allowed.

      Clanguage linkage is not allowed.

      Other than the restrictions above, literal operators and literal operator templates are normal functions (and function templates), they can be declared inline or constexpr, they may have internal or external linkage, they can be called explicitly, their addresses can be taken, etc.

      Run this code
      #include <string> void        operator""_km(longdouble);// OK, will be called for 1.0_kmvoid        operator"" _km(longdouble);// same as above, deprecatedstd::string operator""_i18n(constchar*,std::size_t);// OK template<char...>double operator""_pi();// OKfloat  operator""_e(constchar*);// OK // error: suffix must begin with underscorefloat operator""Z(constchar*); // error: all names that begin with underscore followed by uppercase// letter are reserved (NOTE: a space between "" and _).double operator"" _Z(longdouble); // OK. NOTE: no space between "" and _.double operator""_Z(longdouble); // OK: literal operators can be overloadeddouble operator""_Z(constchar* args); int main(){}

      [edit]Notes

      Since the introduction of user-defined literals, the code that usesformat macro constants for fixed-width integer types with no space after the preceding string literal became invalid:std::printf("%"PRId64"\n",INT64_MIN); has to be replaced bystd::printf("%"PRId64"\n",INT64_MIN);.

      Due tomaximal munch, user-defined integer and floating point literals ending inp,P,(since C++17)e andE, when followed by the operators+ or-, must be separated from the operator with whitespace or parentheses in the source:

      longdouble operator""_E(longdouble);longdouble operator""_a(longdouble);int operator""_p(unsignedlonglong); auto x=1.0_E+2.0;// errorauto y=1.0_a+2.0;// OKauto z=1.0_E+2.0;// OKauto q=(1.0_E)+2.0;// OKauto w=1_p+2;// errorauto u=1_p+2;// OK

      Same applies to dot operator following an integer or floating-point user-defined literal:

      #include <chrono> usingnamespace std::literals; auto a= 4s.count();// Errorauto b= 4s .count();// OKauto c=(4s).count();// OK

      Otherwise, a single invalid preprocessing number token (e.g.,1.0_E+2.0 or4s.count) is formed, which causes compilation to fail.

      Feature-test macroValueStdFeature
      __cpp_user_defined_literals200809L(C++11)User-defined literals

      [edit]Keywords

      operator

      [edit]Examples

      Run this code
      #include <algorithm>#include <cstddef>#include <iostream>#include <numbers>#include <string> // used as conversion from degrees (input param) to radians (returned output)constexprlongdouble operator""_deg_to_rad(longdouble deg){longdouble radians= deg*std::numbers::pi_v<longdouble>/180;return radians;} // used with custom typestruct mytype{unsignedlonglong m;}; constexpr mytype operator""_mytype(unsignedlonglong n){return mytype{n};} // used for side-effectsvoid operator""_print(constchar* str){std::cout<< str<<'\n';} #if __cpp_nontype_template_args < 201911 std::string operator""_x2(constchar* str,std::size_t){returnstd::string{str}+ str;} #else // C++20 string literal operator template template<std::size_t N>struct DoubleString{char p[N+ N-1]{}; constexpr DoubleString(charconst(&pp)[N]){        std::ranges::copy(pp, p);        std::ranges::copy(pp, p+ N-1);}}; template<DoubleString A>constexprauto operator""_x2(){return A.p;} #endif // C++20 int main(){double x_rad=90.0_deg_to_rad;std::cout<<std::fixed<< x_rad<<'\n';     mytype y=123_mytype;std::cout<< y.m<<'\n'; 0x123ABC_print;std::cout<<"abc"_x2<<'\n';}

      Output:

      1.5707961230x123ABCabcabc

      [edit]Standard library

      The following literal operators are defined in the standard library:

      Defined in inline namespacestd::literals::complex_literals
      astd::complex literal representing purely imaginary number
      (function)[edit]
      Defined in inline namespacestd::literals::chrono_literals
      astd::chrono::duration literal representing hours
      (function)[edit]
      astd::chrono::duration literal representing minutes
      (function)[edit]
      astd::chrono::duration literal representing seconds
      (function)[edit]
      astd::chrono::duration literal representing milliseconds
      (function)[edit]
      astd::chrono::duration literal representing microseconds
      (function)[edit]
      astd::chrono::duration literal representing nanoseconds
      (function)[edit]
      astd::chrono::year literal representing a particular year
      (function)[edit]
      astd::chrono::day literal representing a day of a month
      (function)[edit]
      Defined in inline namespacestd::literals::string_literals
      converts a character array literal tobasic_string
      (function)[edit]
      Defined in inline namespacestd::literals::string_view_literals
      creates a string view of a character array literal
      (function)[edit]

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      CWG 1473C++11whitespace between"" andud-suffix was
      required in the declaration of literal operators
      made optional
      CWG 1479C++11literal operators could have default argumentsprohibited
      CWG 2521C++11operator"" _Bq was ill-formed (no diagnostic
      required) because it uses the reserved identifier_Bq
      deprecated the literal operator syntax
      with whitespace between"" andud-suffix
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/user_literal&oldid=182729"

      [8]ページ先頭

      ©2009-2025 Movatter.jp