完美转发模板参数包到emplace_back - 编译失败

时间:2016-06-23 16:39:35

标签: templates c++11 c++14 variadic-templates perfect-forwarding

如果在类似问题中有解决方案,我很难道歉,我找不到具有类似错误输出/问题的解决方案。

我正在尝试编译此代码:

#include <vector>
using namespace std;

template< typename value_type >
class obj
{
    vector<value_type> m_v;
  public:

    template<class... vaList_t>
    void _emplace_back(vaList_t&&... i_values)
    {
        m_v.emplace_back( forward<vaList_t>(i_values)... );
    }
};

int main()
{
  obj<int> thing;
  thing._emplace_back(1,2,3,4);
  return 0;
}

然而,它无法编译:

    In file included from /usr/include/x86_64-linux-gnu/c++/4.9/bits/c++allocator.h:33:0,
                 from /usr/include/c++/4.9/bits/allocator.h:46,
                 from /usr/include/c++/4.9/vector:61,
                 from 1:
/usr/include/c++/4.9/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = int; _Args = {int, int, int, int}; _Tp = int]':
/usr/include/c++/4.9/bits/alloc_traits.h:253:4:   required from 'static std::_Require<typename std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::type> std::allocator_traits<_Alloc>::_S_construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = int; _Args = {int, int, int, int}; _Alloc = std::allocator<int>; std::_Require<typename std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::type> = void]'
/usr/include/c++/4.9/bits/alloc_traits.h:399:57:   required from 'static decltype (_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) std::allocator_traits<_Alloc>::construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = int; _Args = {int, int, int, int}; _Alloc = std::allocator<int>; decltype (_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) = <type error>]'
/usr/include/c++/4.9/bits/vector.tcc:97:40:   required from 'void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {int, int, int, int}; _Tp = int; _Alloc = std::allocator<int>]'
13:3:   required from 'void obj<value_type>::_emplace_back(vaList_t&& ...) [with vaList_t = {int, int, int, int}; value_type = int]'
20:30:   required from here
/usr/include/c++/4.9/ext/new_allocator.h:120:4: error: new initializer expression list treated as compound expression [-fpermissive]
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

问题:

  • 这完全转发模板参数包在语法上是否正确? (如果不是什么?)
  • 实现此行为的正确方法是什么?

提前谢谢。

修改 抱歉任何歧义。我试图用类型签名调用这个名为emplace_back的向量函数:

template< class... Args > void emplace_back( Args&&... args );

带有完美转发的模板参数包,其中包含多个要添加的元素。

例如:

  • &#34; 1,2,3,4&#34; - 在矢量背面添加4个不同的对象 emplace_back
  • &#34;真,假假&#34; - 通过emplace_back
  • 在矢量背面添加3个不同的对象

1 个答案:

答案 0 :(得分:5)

c.emplace_backc中创建单个元素。如果你想要多个,你需要进行emplace_back部分扩展。像这样:

template<class... vaList_t>
void _emplace_back(vaList_t&&... i_values)
{
    int dummy[] = { 0, (m_v.emplace_back(forward<vaList_t>(i_values)), 0)... };
}

[Live example]