[英]We cannot create an std::array from an initializer_list, but can we create it with a helper function with variadic arguments?
Please consider the following vector
class: 请考虑以下
vector
类:
template<typename T, class Tuple = std::vector<T>>
class vector
{
public:
using size_type = typename Tuple::size_type;
template<class T = Tuple, class = std::enable_if_t<std::is_constructible<T, size_type>::value>>
vector(size_type n)
: m_elements(n)
{ }
template<class T = Tuple, class = std::enable_if_t<std::is_constructible<T, std::initializer_list<T>>::value>>
vector(std::initializer_list<T> init)
: m_elements(init)
{ }
private:
Tuple m_elements;
}; // class vector
template<typename T, std::size_t N>
using static_vector = vector<T, std::array<T, N>>;
template<typename T>
static_vector<T, /* N */> make_static_vector(T... elements) { /* ... */ }
The problem is that I want to use std::array
for Tuple
, but std::array
is not constructible from an initialiter_list
. 问题是我想对
Tuple
使用std::array
,但是std::array
无法从initialiter_list
构造。 That's why I've disabled the corresponding constructor of vector
in that case. 这就是为什么我在这种情况下禁用了
vector
的相应构造函数的原因。 (I know that I could use std::copy(init.begin(), init.end(), m_elements.begin()
in either case, but that would yield other problems.) (我知道在两种情况下都可以使用
std::copy(init.begin(), init.end(), m_elements.begin()
,但这会产生其他问题。)
Since I would like to do something like static_vector<double> x = { 1, 2, 3 };
由于我想做一些类似
static_vector<double> x = { 1, 2, 3 };
I thought my best option (feel free to correct me) to provide a helper function like make_static_vector
. 我认为最好的选择(随时纠正我)是提供诸如
make_static_vector
的辅助函数。 (That's not as beautiful as an initializer_list
, so, again, please feel free to come up with a more beautiful solution.) (这不像
initializer_list
那样漂亮,因此,请再次提出更漂亮的解决方案。)
I want to write auto x = make_static_vector<double>(1, 2, 3);
我想写
auto x = make_static_vector<double>(1, 2, 3);
. 。 How do I need to implement it?
我该如何实施?
A simple form looks like this: 一个简单的形式如下所示:
template <typename T,typename... Elements>
static_vector<T, sizeof...(Elements)>
make_static_vector(Elements... elements)
{
return static_vector<T,sizeof...(Elements)>(elements...);
}
You will also need to make a variadic constructor for your vector: 您还需要为向量创建一个可变参数的构造函数:
template <typename... Args>
vector(Args... init)
: m_elements{static_cast<T>(init)...}
{ }
The static_cast
is necessary if you want to avoid narrowing errors using ints where doubles are required. 如果要避免在需要双精度的情况下使用int来缩小错误范围,则需要
static_cast
。
If you want to use perfect forwarding, it's a bit more to type, but it's the same idea. 如果您想使用完美的转发,则需要输入更多内容,但这是相同的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.