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',这似乎不是很有用也不直观.
有了这个,我有两个问题:
std::string
?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)