如何将字符传递给期望字符串的函数

How to pass a char to a function expecting a string

本文关键字:期望 字符串 函数 字符      更新时间:2023-10-16

我想传递一个char给一个期望字符串的参数。

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>&}’

我知道我可以把'改为',但在我的实际代码中,它不是一个字面量。

我如何方便地得到这个编译?

没有从字符到字符串的隐式转换。必须使用适当的构造函数创建字符串,该构造函数有另一个参数来指定长度:

test(std::string(1, 'a'));

或者,从c++ 11开始,使用初始化列表

test({'a'});             // if there are no ambiguous overloads of "test"
test(std::string{'a'});  // if you need to specify the type

你可以像下面的例子那样使用大括号:

#include <string>
#include <iostream>
void test(const std::string&) { std::cout << "test!" << std::endl; }
int main() {
  test({'a'});
}

现场演示

这听起来像是一个消息重载的任务。

void test(const string&);
void test(char);

和在你的类实现中

void yourclass::test(const string& aString)
{
...
}

void yourclass::test(char aChar)
{
  ::test(std::string(1,aChar));
}

嗯,可以自己添加过载吗?

void test(char v)
{ test(string(1, v)); }

编辑:我没有在列表中提到c++ 11的答案,而且我假定您不能修改调用点。如果是后一种情况,并且您没有c++11,那么为此创建一个宏/函数。

void to_string(char v)
{ return string(1, v); }
// Use
test(to_string('c'));

然后您可以处理所有情况(const char*, char*to_string()过载)