嵌套初始化列表的构造函数

6

是否可能拥有一个通用构造函数,可以接受任何类型的初始化列表,即使其中包含嵌套的列表?

假设您有以下部分模板特化的类,它使用其构造函数嵌套初始化列表:

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;
}

此代码打印:

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

现在,我正在尝试概括构造函数,以便我不必为每个维度专门化类模板。 问题是,当我用以下内容替换构造函数时:
template <class L>
ClassA(std::initializer_list<L> l) {
  cout<<"generic list constructor"<<endl;
}
clang编译器出现错误,错误信息如下:
error: no matching constructor for initialization of 'ClassA<4>

有人能解释一下为什么会出现这种情况吗?对于初始化列表,模板匹配无法正常工作,可能是因为这是新的C++特性? 谢谢大家...
编辑: 感谢@JohannesSchaub-litb和@Daniel Frey的帮助,我成功地创建了一个非常通用的构造函数,可以接受任何维度的初始化列表。以下是最终的代码:
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;
}

当然,这段代码会打印输出。
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

我喜欢这个元编程模板!感谢大家帮忙解决问题。
aa
2个回答

6
我相信你真正想做的是自动构建正确类型的内容。
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) 
};

关于为什么您的尝试没有成功,请参见模板并不总是能猜测初始化列表类型


2

一般来说,答案是(据我所知):不行。但是对于您的特定情况,您可以利用所有叶子节点都以double结尾的知识:

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) {}
};

并将您的构造函数更改为:

typedef std::initializer_list<arg_type> initializer_type;

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

希望能对您有所帮助...


更新: 正如Mankarse指出的(感谢!)上述内容存在未定义的行为。这里提供一个版本,应该可以在不使用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 };
}

如果你想尝试它,这里有一个实时示例

不幸的是,这段代码存在未定义行为,因为它使用不完整类型(arg_type)实例化了std::vector。将std::vector替换为boost::container::vector,一切都会好起来。 - Mankarse
@Mankarse:谢谢!我更新了答案,提供了一种不需要Boost库的替代方案。 - Daniel Frey
复制std::initializer_list并不会复制其底层对象。在原始初始化列表对象的生命周期结束后,底层数组不能保证存在。(参见此处)。虽然可能只临时存储或使用初始化列表,但将其复制到向量中似乎更安全和更通用。 - Daniel Frey
我相信他真的想要做我在答案中描述的事情。 - Johannes Schaub - litb
@JohannesSchaub-litb:是可能的,没错。我只是在想,这是否意味着原始示例应该有4^3 = 64个值而不是24个。但好吧,有了你的(好的,+1)答案,OP就有另一个选择。 - Daniel Frey
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接