6

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.

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
Kyle Strand
  • 15,941
  • 8
  • 72
  • 167

1 Answers1

6
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
Community
  • 1
  • 1
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160