检查数组是否为标量类型

Check if array is of scalar types

本文关键字:标量 类型 是否 数组 检查      更新时间:2023-10-16

我希望我的模板类不允许使用非标量类型的数组作为模板参数,为此我编写了以下辅助类型:

template<bool> struct AssertTrue;
template<> struct AssertTrue<true> {};
template < class T>
struct FilterOutArraysWithNonScalarTypes
{
    typedef std::true_type Allowed;
};
template < class T, size_t N>
struct FilterOutArraysWithNonScalarTypes<T[N]>
{
    typedef std::integral_constant<bool, std::is_scalar<T>::value> Allowed;
};

然后在我的对象的构造函数中,我用这种方式检查

CheckAllowance<FilterOutArraysWithNonScalarTypes<T>::Allowed::value>;

我能做得更好吗?

编辑:

对不起,我用CheckAllowance打印错了AssertTrue。

您可以使用单个static_assert:

template <typename T>
struct Foo {
    static_assert(!(std::is_array<T>::value && 
                    !std::is_scalar<std::remove_extent_t<T>>::value),
                  "Must not be a non-scalar array");
};

如果你觉得这太冗长了,你可以制作一个别名模板特征:

template <typename T>
using is_non_scalar_array = std::integral_constant<
                              bool,
                              std::is_array<T>::value && 
                              !std::is_scalar<std::remove_extent_t<T>>::value
                            >;

或者作为变量模板:

template <typename T>
constexpr bool is_non_scalar_array = std::is_array<T>::value && 
                                     !std::is_scalar<std::remove_extent_t<T>>::value;

您所显示的代码中没有使用AssertTrue。我想你可以把它换成static_assert()。否则一切看起来都很好。