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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With