jeudi 23 novembre 2017

Why user-defined string literal and integer literal have different behavior?

I'm learning user-defined literal, and confused with the following test code:

std::chrono::seconds operator"" _s(unsigned long long s) {
    return std::chrono::seconds(s);
}

std::string operator"" _str(const char *s, std::size_t len) {
    return std::string(s, len);
}

int main() {
    auto str = "xxxxx"_str;
    std::cout << str.size() << std::endl;    // works

    auto sec = 4_s;
    std::cout << sec.count() << std::endl;   // works

    std::cout << "xxxxx"_str.size() << std::endl;   // works

    std::cout << 4_s.count() << std::endl;   // **NOT** work!

    return 0;
}

The compiler gives the following error message:

error: no matching literal operator for call to 'operator""_s.count' with argument of type 'unsigned long long' or 'const char *', and no matching literal operator template cout << 4_s.count() << endl;

It seems that it takes _s.count as a user-defined literal. Also, floating-point literal behaviors as integer literal.

Why user-defined integer literal and string literal have different behavior?

Aucun commentaire:

Enregistrer un commentaire