使用clang 3.5.0和gcc 4.9.1编译以下代码,在最后一个语句处会产生错误。
#include <iostream>
struct Foo { Foo(int x, int y) { std::cout << "Foo(int = " << x << ", int = " << y << ")" << std::endl; } };
void bar(int x, int y) { std::cout << "bar(int = " << x << ", int = " << y << ")" << std::endl; }
int main()
{
Foo({}, {}); // Foo(int = 0, int = 0)
Foo({1}, {2}); // Foo(int = 1, int = 2)
Foo({1, 2}); // Foo(int = 1, int = 2)
bar({}, {}); // bar(int = 0, int = 0)
bar({1}, {2}); // bar(int = 1, int = 2)
bar({1, 2}); // error: no matching function for call to 'bar' <<< Why? <<<
}
为什么Foo({1, 2})
是正确的,而bar({1, 2})
不是?
特别是,了解背后的原理会很有帮助。
Foo({1,2})
创建一个临时的 Foo 对象并调用复制构造函数。 - Borgleadervec.insert(vec.back(), {...})
可以很好地工作,与您的代码相反(调用了std::initializer_list
版本)。我刚才写了这个代码,希望 C++ 委员会在实现初始化列表时已经想到了这一点,因此这将 "只需要工作",而且确实如此。这真是太棒了。 - Damon