jeudi 1 décembre 2016

Is it possible to create templated user-defined literals (literal suffixes) for string literals?

I was suprised when I discovered that it's possible to make user-defined literals templated:

template <char ...C> std::string operator ""_s()
{
    char arr[]{C...};
    return arr;
}

// ...

std::cout << 123_s;

But above declaration does not work with string literals:

"123"_s

gives me following error:

prog.cpp: In function 'int main()':
prog.cpp:12:15: error: no matching function for call to 'operator""_s()'
std::cout << "123"_s;

prog.cpp:4:34: note: candidate: template std::string operator""_s()
template std::string operator ""_s()

prog.cpp:4:34: note: template argument deduction/substitution failed:

(Ideone)

Is there is a way to use templated user-defined literals with string literals as well?

Aucun commentaire:

Enregistrer un commentaire