如何正确解决const std :: string&和const std :: vector <string>&ambiguity?

Tob*_*ias 1 c++ overloading c++11

我有一个函数,我有一个像这样的重载:

void process(const std::string& text)
{
}

void process(const std::vector<std::string>& manyTexts)
{
}
Run Code Online (Sandbox Code Playgroud)

我称之为:

process({"hello", "hey"});
Run Code Online (Sandbox Code Playgroud)

我希望这可以解决第二次重载,但这显然是模棱两可的.令我惊讶的是我发现这个要编译:

std::string text = {"hello", "hey"};
Run Code Online (Sandbox Code Playgroud)

变量只包含'hello',这似乎不是很有用也不直观.

有了这个,我有两个问题:

  1. 是什么导致这是一个有效的初始化std::string
  2. 这可以通过某种方式解决,不涉及重命名功能或避免初始化列表?

R S*_*ahu 5

std::string 有一个构造函数:

template< class InputIt >
basic_string( InputIt first, InputIt last, 
              const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

电话

std::string text = {"hello", "hey"};
Run Code Online (Sandbox Code Playgroud)

解析为该构造函数.即使语法调用解析为一个有效的构造函数,这将导致在运行时间,因为不确定的行为"hello""hey"不相关的字符串.

唯一的方法

process({"hello", "hey"});
Run Code Online (Sandbox Code Playgroud)

解决第二个功能是使其显式化.

process(std::vector<std::string>{"hello", "hey"});
Run Code Online (Sandbox Code Playgroud)