抱歉,如果在类似问题中有解决方案,我无法找到错误输出/问题类似的解决方案。

我正在尝试编译以下代码:

#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的 vector 函数:
    template< class... Args > void emplace_back( Args&&... args );
    

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

    例如:
  • “1,2,3,4”-通过将4个不同的对象添加到 vector 的背面
    emplace_back
  • “true,false,false”-通过emplace_back
  • 将3个不同的对象添加到 vector 的背面

    最佳答案

    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]

    10-04 14:29