【问题标题】:Check if array is of scalar types检查数组是否为标量类型
【发布时间】:2015-12-15 15:15:55
【问题描述】:

我希望我的模板类不允许将非标量类型的数组作为模板参数,为此我编写了这些辅助类型:

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。

【问题讨论】:

  • 尝试使用 Boost MPL 库。它有一堆预定义的类和模板。
  • @randomusername 我不能

标签: c++ arrays templates


【解决方案1】:

你可以用一个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;

【讨论】:

    【解决方案2】:

    您的AssertTrue 未在您显示的代码中使用。我想你可以用static_assert() 替换它。否则一切看起来都很好。

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多