从initializer_list初始化向量会产生不清楚的编译错误

问题描述

如果将std::copy注释掉,并将atc初始化程序取消注释,则此代码将编译。

class MyClass {
  MyClass( OtherClass* poc_in,std::initializer_list<ThirdClass> iltc) :
    poc( poc_in)
    //,atc(iltc)
  {
    std::copy( iltc.begin(),iltc.end(),atc );
  }

  OtherClass* poc;
  std::vector<ThirdClass> atc;
}

但是,据我所知:

In file included from /opt/rh/devtoolset-6/root/usr/include/c++/6.3.1/algorithm:61:0,from ../../../src/tester/main.cpp:5:
/opt/rh/devtoolset-6/root/usr/include/c++/6.3.1/bits/stl_algobase.h: In instantiation of '_OI std::__copy_move_a(_II,_II,_OI) [with bool _IsMove = false; _II = const ThirdClass*; _OI = std::vector<ThirdClass>]':
/opt/rh/devtoolset-6/root/usr/include/c++/6.3.1/bits/stl_algobase.h:422:45:   required from '_OI std::__copy_move_a2(_II,_OI) [with bool _IsMove = false; _II = const ThirdClass*; _OI = std::vector<ThirdClass>]'
/opt/rh/devtoolset-6/root/usr/include/c++/6.3.1/bits/stl_algobase.h:455:8:   required from '_OI std::copy(_II,_OI) [with _II = const ThirdClass*; _OI = std::vector<ThirdClass>]'
../../../src/tester/main.cpp:75:59:   required from here
/opt/rh/devtoolset-6/root/usr/include/c++/6.3.1/bits/stl_algobase.h:378:57: error: no type named 'value_type' in 'struct std::iterator_traits<std::vector<ThirdClass> >'
       typedef typename iterator_traits<_OI>::value_type _ValueTypeO;
                                                         ^~~~~~~~~~~
/opt/rh/devtoolset-6/root/usr/include/c++/6.3.1/bits/stl_algobase.h:383:9: error: no type named 'value_type' in 'struct std::iterator_traits<std::vector<ThirdClass> >'
       const bool __simple = (__is_trivial(_ValueTypeI)
                             ~~~~~~~~~~~~~~~~~~~~~~~~~~
                       && __is_pointer<_II>::__value
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                       && __is_pointer<_OI>::__value
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         && __are_same<_ValueTypeI,_ValueTypeO>::__value);
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我已经在Stack Overflow上阅读了六个类似的问题,但是没有人阐明为什么这个版本不受欢迎。有什么建议吗?

解决方法

这与初始化程序列表无关。

您使用的std::copy错误。

第三个参数应该是输出迭代器,而不是向量。

尝试使用std::back_inserter

std::copy( iltc.begin(),iltc.end(),std::back_inserter(atc) );

诚然,编译错误有些深奥,但这是指编译器正在traits帮助器中寻找类型为的成员value_type(大多数迭代器具有 all )您给它的参数(向量)不存在(因为向量不是迭代器)。