Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template alternative for user defined literals

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

My code:

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 user defined literals are limited and cannot be used with most templates such the one above.

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

Note: base can be 2 to 30.

like image 223
Shadi Avatar asked Jan 04 '23 00:01

Shadi


1 Answers

It's actually possible with a bit of indirection. The idea is to delay the template deduction up to the point where you have the 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)};
}

It's an example of the "Return Type Resolver" idiom.

Of course, bear in mind that means that auto a = 345_G will not create a variable of MyClass<> type, although it could be passed to any function which expects one. That can either be a bug or a feature, depending on how you look at it.

like image 84
StoryTeller - Unslander Monica Avatar answered Jan 18 '23 06:01

StoryTeller - Unslander Monica