【发布时间】:2017-05-21 20:40:16
【问题描述】:
如果我想用一个带多个参数的构造函数构造嵌入式 std::string,是否可以构造一个 std::pair?
例如,这是合法的:
#include <iostream>
#include <utility>
#include <string>
int main()
{
std::pair<int, int> pair(2, 3);
return 0;
}
...这是合法的:
#include <iostream>
#include <utility>
#include <string>
int main()
{
std::pair<int, std::string> pair(2, "hello");
return 0;
}
...但我想知道是否可能出现以下情况:
#include <iostream>
#include <utility>
#include <string>
int main()
{
std::pair<int, std::string> pair{2, {"hello", 3}}; //Unclear if some variation/combination of parentheses and curly braces can make this legal.
return 0;
}
我认为以上是使用“统一初始化列表”的正确语法,但这不适用于我的目的,因为我使用的是 C++11 之前的编译器。有没有办法用 C++11 之前的语法来解决这个问题?
为了澄清,我正在尝试使用这个 std::string 构造函数:
basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );
作为我问这个问题的背景,这是出于学术好奇心(如果错了,请纠正我):我认为像这样进行单行构造更有效,因为 std::pair 及其成员只是简单地创建和初始化一口气。而如果我做了这样的事情(使用 C++11 语法)......
#include <iostream>
#include <utility>
#include <string>
int main()
{
std::pair<int, int> pair(2, 3);
std::pair<int, std::string> pair2 = {2, {"hello", 3}};
return 0;
}
...然后我在技术上创建一个std::pair<int, std::string>,其成员是默认构造的,然后调用std::pair 的operator=,然后在该对的成员上调用operator=。
【问题讨论】:
-
std::string("hello",3)?您尝试使用哪个构造函数,为什么? -
@c650:更新帖子以回答您的问题。
标签: c++ string c++11 constructor std-pair