constexpr,数组和初始化 [英] constexpr, arrays and initialization
本文介绍了constexpr,数组和初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++世界中有什么可以让我想做的事情吗?
Is there anything in the world of C++ that would make what I'm trying to do possible?
template < typename T
, size_t Size >
struct array
{
constexpr T buf[Size];
constexpr size_t size() const { return Size; }
};
template < typename T
, size_t Size >
constexpr array<T,Size+1> push_back(array<T,Size> const& arr, T const& val)
{
array<T,Size+1> arr_out = {{arr.buf, val}};
return arr_out;
}
我要做的是创建一个用数据初始化的新数组在另一个,并把一个新的元素在结束。
What I'm trying to do is create a new array initialized with the data in the other, and put a new element on the end.
减少constexpr我可以得到它的工作循环初始化在push_back函数。看来你不能在constexpr函数,这是有一些意义,虽然我认为一个聪明的编译器可以解决这个问题。
Minus the constexpr I can get it to work by loop initializing in the push_back function. It appears you can't do that in constexpr functions, which makes some sense though I think a smart enough compiler could figure that out.
我确定它可以
推荐答案
指数招数,yay〜
template < typename T
, size_t Size >
struct array
{
T buf[Size]; // non-static data members can't be constexpr
constexpr size_t size() const { return Size; }
};
namespace detail{
template< typename T, size_t N, size_t... Is>
constexpr array<T, N+1> push_back(array<T, N> const& arr, T const& val, indices<Is...>)
{
// can only do single return statement in constexpr
return {{arr.buf[Is]..., val}};
}
} // detail::
template < typename T, size_t Size >
constexpr array<T,Size+1> push_back(array<T,Size> const& arr, T const& val)
{
return detail::push_back(arr, val, build_indices<Size>{});
}
这篇关于constexpr,数组和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文