代码之家  ›  专栏  ›  技术社区  ›  Timmmm

解决GCC 5.5元组初始化错误的方法

  •  3
  • Timmmm  · 技术社区  · 6 年前

    考虑以下代码:

      std::vector<
              std::tuple<std::vector<std::size_t>,
                         std::vector<std::size_t>,
                         std::vector<std::size_t>>
            > foo = {
            {{2, 1, 2, 3},   {1, 2},  {2, 3}},
            {{2, 3, 4, 0},   {3},     {2, 3, 4}},
            {{2, 3, 4, 0},   {0},     {3, 4, 0}},
          };
    

    在Clang和GCC 6或更高版本中,它编译得很好。GCC 5.5中给出了以下错误:

     In function 'int main()':
    
    :16:4: error: converting to
              'std::tuple<std::vector<long unsigned int, std::allocator<long unsigned int> >,
                          std::vector<long unsigned int, std::allocator<long unsigned int> >,
                          std::vector<long unsigned int, std::allocator<long unsigned int> > >'
          from initializer list would use explicit constructor
              'constexpr std::tuple< <template-parameter-1-1> >::tuple(const _Elements& ...)
         [with _Elements = {
               std::vector<long unsigned int, std::allocator<long unsigned int> >, std::vector<long unsigned int, std::allocator<long unsigned int> >, std::vector<long unsigned int, std::allocator<long unsigned int> >}]'
    
        };
    
        ^
    

    为什么会这样?我该如何应对?

    1 回复  |  直到 6 年前
        1
  •  3
  •   HolyBlackCat    6 年前

    一种可能的解决方法是调用 tuple 构造函数显式:

    using bar = std::tuple<std::vector<std::size_t>,
                           std::vector<std::size_t>,
                           std::vector<std::size_t>>;
    std::vector<bar> foo = {
        bar{{2, 1, 2, 3},   {1, 2},  {2, 3}},
        bar{{2, 3, 4, 0},   {3},     {2, 3, 4}},
        bar{{2, 3, 4, 0},   {0},     {3, 4, 0}},
    };
    

    (Live demo)