std::initializer_list备选方案

std::initializer_list alternative

本文关键字:方案 initializer std list      更新时间:2023-10-16

我正在尝试初始化我的自定义矢量对象,但没有使用std::initializer_list。我正在做这样的事情:

template <typename T, std::size_t N>
struct vector
{
template<std::size_t I = 0, typename ...Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
unpack_tuple(std::tuple<Tp...> const& t)
{
}
template<std::size_t I = 0, typename ...Tp>
typename std::enable_if<I != sizeof...(Tp), void>::type
unpack_tuple(std::tuple<Tp...> const& t)
{
store[I] = std::get<I>(t);
unpack_tuple<I + 1, Tp...>(t);
}
template<typename ...U>
vector(U&&... args,
typename std::enable_if<std::is_scalar<U...>::value, void>::type* = 0)
{
unpack_tuple(std::forward_as_tuple(std::forward<U>(args)...));
}
T store[N];
};

但是编译器不会对构造函数进行grok,除非我删除std::enable_if参数,我需要它(因为我不想要非标量参数)。是否存在解决方案?

std::is_scalar<U...>::value

问题在于is_scalar只接受一个类型参数。您需要编写一个组合多个布尔值的包装器。我还想知道,如果你只想要标量类型,为什么要使用完美转发——只需按值传递它们。通过这种方式,您也不需要担心在传递左值时U会被推导为引用。

#include <type_traits>
template<bool B>
using bool_ = std::integral_constant<bool, B>;
template<class Head, class... Tail>
struct all_of
: bool_<Head::value && all_of<Tail...>::value>{};
template<class Head>
struct all_of<Head> : bool_<Head::value>{};
template<class C, class T = void>
using EnableIf = typename std::enable_if<C::value, T>::type;
// constructor
template<typename... U>
vector(U... args, EnableIf<all_of<std::is_scalar<U>...>>::type* = 0)
{
unpack_tuple(std::tie(args...)); // tie makes a tuple of references
}

上面的代码应该可以工作。然而,作为一个建议,如果你不想要什么,static_assert你没有得到,不要因此滥用SFINAE。:)SFINAE只能在重载上下文中使用。

// constructor
template<typename... U>
vector(U... args)
{
static_assert(all_of<std::is_scalar<U>...>::value, "vector only accepts scalar types");
unpack_tuple(std::tie(args...)); // tie makes a tuple of references
}

您的实际问题到此为止,但我建议使用索引技巧来解包元组(或一般的可变参数,甚至数组)的更好方法:

template<unsigned...> struct indices{};
template<unsigned N, unsigned... Is> struct indices_gen : indices_gen<N-1, N-1, Is...>{};
template<unsigned... Is> struct indices_gen<0, Is...> : indices<Is...>{};
template<unsigned... Is, class... U>
void unpack_args(indices<Is...>, U... args){
[](...){}((store[Is] = args, 0)...);
}
template<class... U>
vector(U... args){
static_assert(all_of<std::is_scalar<U>...>::value, "vector only accepts scalar types");
unpack_args(indices_gen<sizeof...(U)>(), args...);
}

此代码所做的是"滥用"可变的拆包机制。首先,我们生成一组索引[0 .. sizeof...(U)-1],然后与args同步扩展此列表。我们把这个扩展放在一个可变(非模板)函数参数列表中,因为包扩展只能发生在特定的地方,这就是其中之一。另一种可能是作为本地阵列:

template<unsigned... Is, class... U>
void unpack_args(indices<Is...>, U... args){
int a[] = {(store[Is] = args, 0)...};
(void)a; // suppress unused variable warnings
}
相关文章: