Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`using` declaration for a user-defined literal operator

Is it possible to have a using declaration for the literals operator, operator ""?

E.g.,

#include <chrono>

namespace MyNamespace
{
  constexpr std::chrono::hours operator "" _hr(unsigned long long n){
    return std::chrono::hours{n};
  }

  // ... other stuff in the namespace ...
}

using MyNamespace::operator"";    // DOES NOT COMPILE!

int main()
{
  auto foo = 37_hr;
}

My work-around has been to put these operators in their own nested namespace called literals, which allows using namespace MyNamespace::literals;, but this seems somewhat inelegant, and I don't see why the using directive can't be used for operator functions in the same way as it can for any other functions or types within a namespace.

like image 380
Kyle Strand Avatar asked Aug 31 '15 20:08

Kyle Strand


People also ask

What is the function called by a user-defined literal?

The function called by a user-defined literal is known as literal operator (or, if it's a template, literal operator template).

How are user-defined literal expressions treated in overload sets?

If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function call operator "" X("n")

What are user-defined literals in C++11?

(C++11) Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix. A user-defined literal is an expression of any of the following forms an identifier, introduced by a literal operator or a literal operator template declaration (see below).

What are the restrictions of a literal operator template?

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.


1 Answers

using MyNamespace::operator""_hr;
//                           ^^^

DEMO

Grammar reference:

using-declaration:
   using typename (opt) nested-name-specifier unqualified-id ;
   using :: unqualified-id ;

unqualified-id:
   identifier
   operator-function-id
   conversion-function-id
   literal-operator-id
   ~ class-name
   ~ decltype-specifier
   template-id

literal-operator-id:
   operator string-literal identifier
   operator user-defined-string-literal
like image 193
Piotr Skotnicki Avatar answered Nov 05 '22 18:11

Piotr Skotnicki