I want to pass a char to a parameter expecting a string.
void test(const string&);
test('a'); // does not like
error: invalid user-defined conversion from ‘char’ to ‘const string& {aka const std::basic_string<char>&}’
I know I can change ' to ", but in my real code it's not a literal at that point.
How can I conveniently get this to compile?
There's no implicit conversion from a character to a string. You'll have to make a string using the appropriate constructor, which has another parameter to specify the length:
test(std::string(1, 'a'));
or, since C++11, with an initialiser list
test({'a'}); // if there are no ambiguous overloads of "test"
test(std::string{'a'}); // if you need to specify the type
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments