【问题标题】:templated array of duplicate elements without default constructor [duplicate]没有默认构造函数的重复元素的模板化数组[重复]
【发布时间】:2014-01-24 19:39:14
【问题描述】:

当元素类型没有默认构造函数时,有没有办法构造一个包含所有重复元素的模板化元素数组?

我尝试了以下方法:

template<typename T, int n> struct Array {
    template<typename... Args> explicit Array(const T& arg1, Args... args)
        : m_a{arg1, args...} { }
    static Array<T,n> all(const T& value) {
        Array<T,n> ar; // error: use of deleted function 'Array<TypeWithoutDefault, 10>::Array()'
        for (int i=0; i<n; i++)
            ar.m_a[i] = value;
        return ar;
    }
    T m_a[n];
};

struct TypeWithoutDefault {
    TypeWithoutDefault(int i) : m_i(i) { }
    int m_i;
};

int main() {
    // works fine
    Array<TypeWithoutDefault,2> ar1 { TypeWithoutDefault{1}, TypeWithoutDefault{2} };
    (void)ar1;
    // I want to construct an Array of n elements all with the same value.
    // However, the elements do not have a default constructor.
    Array<TypeWithoutDefault,10> ar2 = Array<TypeWithoutDefault, 10>::all(TypeWithoutDefault(1));
    (void)ar2;
    return 0;
}

【问题讨论】:

  • 好吧,您需要repeat 功能。看看我的回答:How to initialize std::array<T, n> elegantly if T is not default constructible?
  • 让我知道这是否也适合您。如果没有,我会修改它,并将其作为答案发布。
  • 谢谢,不幸的是,正如几个人指出的那样,我的问题是重复的。 @Nawaz 和 @Jarod42 的回答都非常合适。 index_sequencemake_index_sequence 的简洁结构非常好。

标签: c++ arrays templates c++11 initialization


【解决方案1】:

以下将解决您的问题:

#if 1 // Not in C++11

template <std::size_t ...> struct index_sequence {};

template <std::size_t I, std::size_t ...Is>
struct make_index_sequence : make_index_sequence<I - 1, I - 1, Is...> {};

template <std::size_t ... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> {};

#endif

namespace detail
{
    template <typename T, std::size_t ... Is>
    constexpr std::array<T, sizeof...(Is)> create_array(T value, index_sequence<Is...>)
    {
        // cast Is to void to remove the warning: unused value
        return {{(static_cast<void>(Is), value)...}};
    }
}

template <std::size_t N, typename T>
constexpr std::array<T, N> create_array(const T& value)
{
    return detail::create_array(value, make_index_sequence<N>());
}

所以测试一下:

struct TypeWithoutDefault {
    TypeWithoutDefault(int i) : m_i(i) { }
    int m_i;
};

int main()
{
    auto ar1 = create_array<10>(TypeWithoutDefault(42));
    std::array<TypeWithoutDefault, 10> ar2 = create_array<10>(TypeWithoutDefault(42));

    return 0;
}

【讨论】:

  • 无需在{{(static_cast&lt;void&gt;(Is), value)...}}; 中使用强制转换。你可以使用{{(Is, value)...}};。保持简单!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 2011-07-15
  • 2015-07-24
  • 2020-05-19
  • 2016-07-07
  • 2014-02-05
  • 1970-01-01
相关资源
最近更新 更多