【问题标题】:DRY way to construct all elements of an array with the same initializer list?用相同的初始化列表构造数组的所有元素的干方法?
【发布时间】:2017-05-11 21:34:13
【问题描述】:

在 C++11 中,是否有一种 DRY 方法来构造数组的所有元素,所有元素都具有相同的一组参数? (例如,通过单个初始化列表?)

例如:

class C {
public:
   C() : C(0) {}
   C(int x) : m_x{x} {}
   int m_x;
};

// This would construct just the first object with a parameter of 1.
// For the second and third object the default ctor will be called.
C ar[3] {1};

// This would work but isn't DRY (in case I know I want all the elements in the array to be initialized with the same value.
C ar2[3] {1, 1, 1};

// This is DRYer but obviously still has repetition.
const int initVal = 1;
C ar3[3] {initVal, initVal, initVal};

我知道使用std::vector 可以轻松实现我的目标。我想知道原始数组是否也可以。

【问题讨论】:

  • 也许是一个小助手模板?
  • 你的默认构造函数是非常邪恶的。
  • 取消它。
  • @Danra:为什么不委托:C() : C(0) {} 以公共术语记录默认构造函数。
  • 完成,谢谢。 (也可以只做一个带有默认参数值的ctor,不想过多改变原问题的语义)

标签: c++ arrays c++11 constructor initializer-list


【解决方案1】:

c++14 - 一点点工作就可以让 c++11 工作了

#include <iostream>
#include <array>
#include <utility>

class C {
public:
    C() : C(0) {}
    C(int x) : m_x{x} {}
    int m_x;
};

namespace detail {
    template<class Type, std::size_t...Is, class...Args>
    auto generate_n_with(std::index_sequence<Is...>, const Args&...args)
    {
        return std::array<Type, sizeof...(Is)> {
            {(void(Is), Type { args... })...} // Or replace '{ args... }' with '( args... )'; see in comments below.
        };
    }
}

template<class Type, std::size_t N, class...Args>
auto generate_n_with(const Args&...args)
{
    return detail::generate_n_with<Type>(std::make_index_sequence<N>(), args...);
}

int main()
{
    auto a = generate_n_with<C, 3>(1);
    for (auto&& c : a)
    {
        std::cout << c.m_x << std::endl;
    }
}

结果:

1
1
1

我要保证c++17之前没有副本

你需要生成一个向量:

template<class Container, class...Args>
auto emplace_n(Container& c, std::size_t n, Args const&...args)
{
    c.reserve(n);
    while(n--) {
        c.emplace_back(args...);
    }
};

这样使用:

std::vector<C> v2;
emplace_n(v2, 3, 1);

【讨论】:

  • 直到 c++17 没有保证复制省略,所以这实际上可能会导致在generate_n_with 中生成数组的副本,不是吗? :)
  • 是的,我知道这就是 +1 的原因,但我只是想知道您是否认为有办法以某种方式内联初始化数组?
  • @W.F.对于向量,是的。对于数组,没有。将编辑以包含矢量版本。
  • 有人能解释一下generate_n_with 中数组的聚合初始化发生了什么吗? {(void(Is), Type { args... })...}
  • @Dana 上面的扩展依赖于 2 个 thibgs。首先是 ... 运算符的范围仅限于在大括号或方括号内扩展。第二个是使用逗号操作符强制 Is 的扩展,没有副作用。就是说Is只用来驱动外...
【解决方案2】:

您可以使用std::index_sequence&lt;...&gt; 构造元素序列,并将其扩展为数组的初始值设定项。不过,我不知道有什么方法可以避免使用辅助功能。这是一个例子:

#include <iterator>
#include <algorithm>
#include <iostream>

struct S {
    int value;
    S(int value): value(value) {}
};
std::ostream& operator<< (std::ostream& out, S const& s) {
    return out << s.value;
}

#include <array>
#include <iterator>
#include <algorithm>
#include <iostream>

struct S {
    int value;
    S(int value): value(value) {}
};
std::ostream& operator<< (std::ostream& out, S const& s) {
    return out << s.value;
}

template <typename T, std::size_t... I>
std::array<T, sizeof...(I)> fill_aux(T value, std::index_sequence<I...>)
{
    return std::array<T, sizeof...(I)>{ (void(I), value)... };
}
template <std::size_t N, typename T>
std::array<T, N> fill(T value) {
    return fill_aux(value, std::make_index_sequence<N>());
}

int main()
{
    std::array<S, 10> array = fill<10>(S(17));
    std::copy(array.begin(), array.end(), std::ostream_iterator<S>(std::cout, " "));
}

【讨论】:

  • 在我看来fill&lt;N&gt;(init)(它返回一个大小为N 的std::array,其中的元素由init 构造)将是对STL 的一个很好的补充。或者,只需向std::array 添加一个构造函数,它采用init,类似于std::vector 的构造函数(显然没有size 参数)。
【解决方案3】:

通过创建派生类,您可以有效地创建新的默认值。这有点骇人听闻,但可能比其他解决方案少骇人听闻。这是一个例子:

class C {
public:
   C() : C(0) {}
   C(int x) : m_x{x} {}
   int m_x;
};


template <int init>
struct CInit : C { CInit() : C(init) {} };

CInit<1> ar2[3];


const int initVal = 1;
CInit<initVal> ar3[3];

另一种方法是使用可变参数构造函数将原始数组包装在结构中:

template <size_t n>
struct Array {
    C array[n];

    template <size_t... seq>
    Array(int init,std::index_sequence<seq...>)
    : array{(void(seq),init)...}
    {
    }

    Array(int init)
    : Array(init,std::make_index_sequence<n>())
    {
    }
};


const int initVal = 1;
Array<3> ar3_1(initVal);
const C (&ar3)[3] = ar3_1.array;

【讨论】:

    【解决方案4】:

    根据理查德的回答,也可以定义

    template<class Type, std::size_t N, class...Args>
    auto generate_n_with(const std::array<Type, N>&, const Args&...args)
    {
        return detail::generate_n_with<Type>(std::make_index_sequence<N>(), args...);
    };
    

    允许你将数组作为参数输入,以使代码更干,以防你已经知道数组的类型,例如

    class D {
    public:
        D();
        std::array<int, 3> m_ar;
    };
    

    允许

    D::D() : m_ar{generate_n_with{m_ar, 5}} {}
    

    而不是干燥的少

    D::D() : m_ar{generate_n_with<int, 3>{5}} {}
    

    附:也许有一种更干燥的方式,无需重复m_ar 两次?

    【讨论】:

    • @RichardHodges 非常感谢您的反馈
    猜你喜欢
    • 2013-07-12
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多