如何初始化 std::array<T, n>如果 T 不是默认可构造的,那么优雅吗?
我如何初始化 std::array<T, n>
如果 T 不是默认可构造的?
我知道可以这样初始化它:
T t{args};std::array<T, 5>一个{t,t,t,t,t};
但 n
对我来说是模板参数:
template无效 f(T 值){std::array<T,N>项目 = ???}
而且即使它不是模板,如果 n
太大,手动重复值也是相当难看的.
给定 N,你可以生成一个名为 code> 使用名为 其中 其余的定义为: 在线演示 希望对您有所帮助. How do I initialize I know it's possible to initialize it like that: But And even if it wasn't template, it's quite ugly to repeat value by hand if Given N, you could generate a sequence-type called where And the rest is defined as: Online demo Hope that helps.seq<0,1,2,3,...N-1>的序列类型
genseq_t<>
的生成器,然后执行以下操作:template
repeat
定义为:template
模板
std::array<T, n>
if T is not default constructible?T t{args};
std::array<T, 5> a{t, t, t, t, t};
n
for me is template parameter:template<typename T, int N>
void f(T value)
{
std::array<T, N> items = ???
}
n
is too large.seq<0,1,2,3,...N-1>
using a generator called genseq_t<>
, then do this:template<typename T, int N>
void f(T value)
{
//genseq_t<N> is seq<0,1,...N-1>
std::array<T, N> items = repeat(value, genseq_t<N>{});
}
repeat
is defined as:template<typename T, int...N>
auto repeat(T value, seq<N...>) -> std::array<T, sizeof...(N)>
{
//unpack N, repeating `value` sizeof...(N) times
//note that (X, value) evaluates to value
return {(N, value)...};
}
template<int ... N>
struct seq
{
using type = seq<N...>;
static const std::size_t size = sizeof ... (N);
template<int I>
struct push_back : seq<N..., I> {};
};
template<int N>
struct genseq : genseq<N-1>::type::template push_back<N-1> {};
template<>
struct genseq<0> : seq<> {};
template<int N>
using genseq_t = typename genseq<N>::type;
相关文章