Alternative to template for custom literals

I created a template class, and I wanted to use user-defined literals.

My code is:

template<int base = 10>
class MyClass
{
   // class code
};

// template<int base> /* Not allowed */
MyClass<17> operator "" _G(const char* param, size_t length)
{
    string temp(param, length);
    return MyClass<17> (temp);
}

int main()
{
    MyClass<17> A = "75AD"_G;
    A.print();
}

As a result of my search, I knew that user-defined user literals are limited and cannot be used with most templates like the ones above.

Is there an alternative solution, or are custom literals impossible in this case?

Note: basemay be from 2to 30.

+4
source share
1 answer

In fact, this is possible with some indirectness. The idea is to defer the deduction of the pattern until you have type information.

struct MyClassCtor {
  std::string param;

  template<int base>
  operator MyClass<base>() {
    return param;
  }
};

MyClassCtor operator "" _G(const char* param, size_t length)
{
    return {std::string(param, length)};
}

" Resolver" .

, , auto a = 345_G MyClass<>, , . , , .

+9

Source: https://habr.com/ru/post/1677738/


All Articles