相关疑难解决方法(0)

转发初始化列表表达式

初始化列表表达式非常便于初始化C++容器:

std::vector<int>({1, 2, 3})
Run Code Online (Sandbox Code Playgroud)

......但似乎一个括号内的初始化列表表达式,如{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})
}
Run Code Online (Sandbox Code Playgroud)

这输出:

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’
Run Code Online (Sandbox Code Playgroud)

(这是GCC 4.7.2的结果.)

遗憾的是,这意味着我们无法转发初始化列表表达式.既然这样做很方便,我想问为什么这不起作用?为什么括号封闭的初始化列表表达式不能绑定到转发引用?或者这是允许的,也许我的编译器太老了?

c++ templates initializer-list c++11

11
推荐指数
2
解决办法
3456
查看次数

标签 统计

c++ ×1

c++11 ×1

initializer-list ×1

templates ×1