在 C++11 中,我们现在可以在函数参数中动态构造对象。
例如,我们可以像这样将一个新对插入到 std::map 中:
typedef std::map<char, int> MapType;
MapType my_map;
my_map.insert({'f', 6}); //less verbose than make_pair
这也适用于 std::vector。然而,对于 std::array 来说,这奇怪地不起作用。
例子:
#include <iostream>
#include <array>
#include <vector>
using namespace std;
void arr_on_fly(std::array<int, 4> arr)
{
/*...*/
}
void vec_on_fly(std::vector<int> vec)
{
/*...*/
}
int main()
{
vec_on_fly({1, 2, 3, 4});
arr_on_fly({1, 2, 3, 4});
}
为什么这不起作用?这是 C++11 标准的缺陷吗?
错误“无法将‘{1、2、3、4}’转换为‘std::array’”似乎很荒谬,因为我们可以像这样初始化一个 std::array:
std::array<int, 4u> arr = {1, 2, 3, 4};
最佳答案
我不知道这种不一致的原因。但是添加额外的大括号可以编译。
arr_on_fly({{1, 2, 3, 4}});
关于C++11 即时构造不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9162272/