其他分享
首页 > 其他分享> > c – DRY方法构造具有相同初始化列表的数组的所有元素?

c – DRY方法构造具有相同初始化列表的数组的所有元素?

作者:互联网

在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可以轻松实现我的目标.我想知道原始数组是否可行.

解决方法:

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

I want to guarantee no copies prior to 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,c11,arrays,constructor,initializer-list
来源: https://codeday.me/bug/20190823/1701941.html