Constructor for nested initializer lists

核能气质少年 提交于 2019-12-05 01:43:03

问题


Is it possible to have a generic constructor that takes any type of initializer list, even if this has nested lists within?

Say you have the following partial template specialization for a class that takes in its constructor nested initializer lists:

template class ClassA;

template <>
class ClassA<4> {

  typedef std::initializer_list<double> list_type;
  typedef std::initializer_list<list_type> llist_type;
  typedef std::initializer_list<llist_type> lllist_type;
  typedef std::initializer_list<lllist_type> initializer_type;

  size_t n_[4] = {0};
  double* data_;

public:

  ClassA(initializer_type l) {

    assert(l.size() > 0);
    assert(l.begin()->size() > 0);
    assert(l.begin()->begin()->size() > 0);
    assert(l.begin()->begin()->begin()->size() > 0);

    size_t m = n_[0] = l.size();
    size_t n = n_[1] = l.begin()->size();
    size_t o = n_[2] = l.begin()->begin()->size();
    n_[3] = l.begin()->begin()->begin()->size();

    data_ = new double[m*n*o*n_[3]];

    int i=0, j=0, k=0, p=0;
    for (const auto& u : l) {
      assert(u.size() == n_[1]);
      for (const auto& v : u) {
        assert(v.size() == n_[2]);
        for (const auto& x : v) {
          assert(x.size() == n_[3]);
          for (const auto& y : x) {
            data_[i + m*j + m*n*k + m*n*o*p] = y;
            ++p;
          }
          p = 0;
          ++k;
        }
        k = 0;
        ++j;
      }
      j = 0;
      ++i;
    }
  }

  size_t size() const {
    size_t n = 1;
    for (size_t i=0; i<4; ++i)
      n *= n_[i];
    return n;
  }

  friend std::ostream& operator<<(std::ostream& os, const ClassA& a) {
    for (int i=0; i<a.size(); ++i)
      os<<" "<<a.data_[i];
    return os<<endl;
  }

};


int main()
{

  ClassA<4> TT = { {{{1.}, {7.}, {13.}, {19}}, {{2}, {8}, {14}, {20}}, {{3}, {9}, {15}, {21}}}, {{{4.}, {10}, {16}, {22}}, {{5}, {11}, {17}, {23}}, {{6}, {12}, {18}, {24}}} };
  cout<<"TT -> "<<TT<<endl;

  return 0;
}

This code prints:

TT ->  1 4 2 5 3 6 7 10 8 11 9 12 13 16 14 17 15 18 19 22 20 23 21 24

Now, I'm trying to generalize the constructor so that I don't have to specialize the class template for each dimension. The problem is that when I replace the constructor with something like:

template <class L>
ClassA(std::initializer_list<L> l) {
  cout<<"generic list constructor"<<endl;
}

The clang compiler fails with error:

error: no matching constructor for initialization of 'ClassA<4>

Can someone point out why is this happening? The template matching is not working for initializer lists, probably because this is a new C++ feature? Thank you all...

EDIT

Thanks to the help of @JohannesSchaub-litb and @Daniel Frey, I was able to craft a very generic constructor that takes the initializer_list of any dimension. This is the resulting code:

template <int d, typename T>
class ClassA {

  size_t n_[d] = {0};
  T* data_;

  template <int D, typename U>
  struct Initializer_list {

    typedef std::initializer_list<typename Initializer_list<D-1,U>::list_type > list_type;

    Initializer_list(list_type l, ClassA& a, size_t s, size_t idx) {

      a.n_[d-D] = l.size();

      size_t j = 0;
      for (const auto& r : l)
        Initializer_list<D-1, U> pl(r, a, s*l.size(), idx + s*j++);
    }
  };

  template <typename U>
  struct Initializer_list<1,U> {

    typedef std::initializer_list<T> list_type;

    Initializer_list(list_type l, ClassA& a, size_t s, size_t i) {

      a.n_[d-1] = l.size();
      if (!a.data_)
        a.data_ = new T[s*l.size()];

      size_t j = 0;
      for (const auto& r : l)
        a.data_[i + s*j++] = r;
    }
  };

  typedef typename Initializer_list<d,T>::list_type initializer_type;

public:

  // initializer list constructor
  ClassA(initializer_type l) : data_(nullptr) {
    Initializer_list<d, T> r(l, *this, 1, 0);
  }

  size_t size() const {
    size_t n = 1;
    for (size_t i=0; i<4; ++i)
      n *= n_[i];
    return n;
  }

  friend std::ostream& operator<<(std::ostream& os, const ClassA& a) {
    for (int i=0; i<a.size(); ++i)
      os<<" "<<a.data_[i];
    return os<<endl;
  }
};

int main()
{

  ClassA<4, double> TT = { {{{1.}, {7.}, {13.}, {19}}, {{2}, {8}, {14}, {20}}, {{3}, {9}, {15}, {21}}}, {{{4.}, {10}, {16}, {22}}, {{5}, {11}, {17}, {23}}, {{6}, {12}, {18}, {24}}} };
  cout<<"TT -> "<<TT<<endl;

  return 0;
}

Of course the code prints

TT ->  1 4 2 5 3 6 7 10 8 11 9 12 13 16 14 17 15 18 19 22 20 23 21 24

I love this template metaprogramming stuff! Thank you guys for helping figuring this out.

aa


回答1:


I believe what you really want to do is to automatically build the right type

template<int S, typename E>
class make_list_type {
public:
  typedef std::initializer_list<
    typename make_list_type<S-1, E>::type
  > type;
};

template<typename E>
class make_list_type<0, E> {
public:
  typedef E type;
};

template<int S>
class ClassA {
  typedef typename make_list_type<S, double>::type initializer_type;

public:
  ClassA(initializer_type l) 
};

As for why your try did not work, see Templates don't always guess initializer list types




回答2:


In general, the answer is (AFAIK): No. But for your specific case, you might use the knowledge that it all ends with double as the leafs:

class arg_type
{
private:
    bool is_value;
    double d;
    std::vector<arg_type> subs;
public:
    arg_type(double v) : is_value(true), d(v) {}
    arg_type(std::initializer_list<arg_type> l) : is_value(false), subs(l) {}
};

and change your ctor to:

typedef std::initializer_list<arg_type> initializer_type;

ClassA(initializer_type l) {
  // ...
}

Hope it helps...


Update: As pointed out by Mankarse (thanks!), the above has undefined behaviour. Here's a version that should fix it without using Boost:

#include <vector>
#include <memory>
#include <iostream>
#include <initializer_list>

class arg_type
{
private:
    std::shared_ptr<void> subs; // empty => d is valid
    double d;

public:
    arg_type(double v) : d(v) {}
    arg_type(std::initializer_list<arg_type> l);

    void print() const;
};

arg_type::arg_type(std::initializer_list<arg_type> l)
  : subs(std::make_shared<std::vector<arg_type>>(l))
{}

void arg_type::print() const
{
   if( subs ) {
     std::cout << "( ";
     for( const auto& e : *std::static_pointer_cast<std::vector<arg_type>>(subs) ) {
       e.print();
     }
     std::cout << ") ";
   }
   else {
      std::cout << d << " ";
   }
}

struct MyClass
{
   MyClass( std::initializer_list<arg_type> l) {
      for( const auto& e : l ){
         e.print();
      }
   }
};

int main()
{
   MyClass m { 1, 2, { 3, 4, { 6, 7, { 8 }}}, 5 };
}

If you want to play with it, here's the live example.



来源:https://stackoverflow.com/questions/15848781/constructor-for-nested-initializer-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!