初始化列表表达式是初始化C++容器真是太方便了:转发初始化列表表达式
std::vector<int>({1, 2, 3})
...但它似乎是一个括号内的初始化列表表达式,如{1,2,3}
将只绑定到一个函数这需要一个std::initializer_list<int>
- 它不似乎绑定到通用(转发)参考:
template <class T>
void foo(T&& v)
{
std::vector<int>(std::forward<T>(v));
}
int main()
{
foo({1, 2, 3})
}
个
此输出:
test2.cpp:11:6: note: template<class U> void foo(U&&)
test2.cpp:11:6: note: template argument deduction/substitution failed:
test2.cpp:33:13: note: couldn't deduce template parameter ‘U’
(这与GCC 4.7.2的结果。)
这不幸意味着我们不能转发初始化列表表达。既然这样做会非常方便,我想问问为什么这不起作用?为什么大括号初始化程序列表表达式不能绑定到转发引用?或者这是允许的,也许我的编译器太老了?
转发'initializer_list'没有用:它已经有引用语义,其元素是const的,因此不可移动。 – dyp 2015-02-06 17:07:10
无关紧要,它们是否可移动 - 通用转发参考不一定意味着移动,它只是意味着沿参数转发,因为 – Siler 2015-02-06 17:08:12
是的,但是braced-init-list没有类型。因此,你不能“原样”转发它。 – dyp 2015-02-06 17:09:05