Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error when using a member of a user-defined literal

When compiling this code (without any header)

template <typename T>
struct Temperature {
    T temp;

    explicit Temperature(T t)
        : temp(t)
    {}
};

Temperature<long double> operator "" _f (long double t)
{
    return Temperature<long double>((t - 32) / 1.8);
}

int main()
{
    auto t = 100.0_f;
    t.temp;

    100.0_f.temp; // ERROR AT THIS LINE
    return 0;
}

The compilers (both g++ 4.8 and clang++ 3.4 on Ubuntu 14.04) will complain that

error: unable to find numeric literal operator ‘operator"" _f.temp’
     100.0_f.temp;
     ^

It seems that the _f.temp is considered as a suffix there. Why do the compilers parse it like that, instead of stopping at the dot?

like image 778
neuront Avatar asked Jun 29 '16 05:06

neuront


People also ask

What is user-defined character literal?

In source code, any literal, whether user-defined or not, is essentially a sequence of alphanumeric characters, such as 101 , or 54.7 , or "hello" or true . The compiler interprets the sequence as an integer, float, const char* string, and so on.

What are literals C++?

C++ Literals. Literals are data used for representing fixed values. They can be used directly in the code. For example: 1 , 2.5 , 'c' etc. Here, 1 , 2.5 and 'c' are literals.

What is string literal operator?

A string literal or anonymous string is a string value in the source code of a computer program. In modern programming languages usually use a quoted sequence of characters, formally "bracketed delimiters", as in x = "foo" .


1 Answers

Preprocessing numbers are odd beasts, specified mostly to make the preprocessor easier to write.

pp-number:
    digit
    . digit
    pp-number digit
    pp-number identifier-nondigit
    pp-number ' digit
    pp-number ' nondigit
    pp-number e sign
    pp-number E sign
    pp-number p sign
    pp-number P sign
    pp-number .

12 is a valid pp-number token, so is 0xe+foo (see the example in [lex.pptoken]/4), and so is .12.CA'TS_RULE..56.me+owp-urr. If the latter two make it past translation phase 6, then the program is ill-formed because it cannot be converted to a valid token in phase 7. Until then, however, it is valid, so maximal munch says we parse 0xe+foo or 100.0_f.temp as a single preprocessing token.

like image 70
T.C. Avatar answered Oct 28 '22 16:10

T.C.