简体   繁体   中英

Why can't the literal operator be templated normally?

I'm currently working on a compile time expression tree and wanted to use a literal operator to create an expression from a literal. Since all literals are allowed as an expression I wanted to template the literal operator like:

template <typename T>
constexpr auto operator""_ve(T value)
{
    return value_expression(value);
}

This didn't compile so I did some research and found out that the only allowed template is

template <char...> XYZ operator "" _abc();

Why is that? Do I really have to specify each overload manually?

Do I really have to specify each overload manually?

Yes.

Literal operators are not called via overload resolution (not really). Overload resolution can do things like allow for implicit conversions or other unpleasant things. Because literal operators are (typically) invoked by the compiler on compile-time-generated values, it's a good idea to make sure that the writer of a literal operator gets the entire literal value (as best as the compiler can provide, of course), not a converted value.

This is actually quite important. Consider the case where you want to write a literal that takes integer values but not floating-point values. That is, 12.3_lit should be a compile error. Your signature for your operator would take unsigned long long , but a long double is implicitly convertible to an unsigned long long . Therefore, 12.3_lit would be valid when you don't want it to be.

Now in theory you could avoid such scenarios by = delete ing floating-point signatures explicitly. But... UDLs were invented at a time when = delete wasn't really a thing, so that wasn't necessarily an option.

To avoid these scenarios, the literal operator dispatch logic explicitly looks for a particular set of signatures (based on the kind of literal being processed). If you don't have a long double overload for the operator (or a raw literal version), then upon encountering 12.3_lit , the system will find no appropriate function and generate a compile error.

Because the system searches for specific signatures rather than using overload resolution, literal operator signatures (including templates) are restricted to being exactly and only the signatures that the literal operator dispatch logic will search for . No more, no less.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM