检查数组是否为标量类型
Check if array is of scalar types
我希望我的模板类不允许使用非标量类型的数组作为模板参数,为此我编写了以下辅助类型:
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()
。否则一切看起来都很好。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 特征中的自定义标量类型
- 标量类型的特征模板无法编译固定大小的子矩阵操作
- 请求从"点*"转换为非标量类型"点"
- 标量类型上的特征模板
- 错误:在 C++ 中从 'Counter' 转换为非标量类型'CountDn'
- 特征:从数组类型中获取标量类型是否记录?
- 错误:请求从"Mstream"转换为非标量类型"std::string {aka std::basic_string<char>}"
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- 错误:移动文件时'QString'为非标量类型"std::__cxx11::字符串"
- 标量类型附加C++
- 复制初始化 - 从 'int' 类型转换为非标量类型
- 在 opencv 上将 vec 类型转换为标量类型
- 为矢量对象请求转换为非标量类型
- 错误:请求从 std::chrono::time_point 浮点数转换为非标量类型长整型
- 此错误的含义是什么:从 'char* [40] 转换为非标量类型 'std::string
- 小标量类型和谷歌协议缓冲区
- 我可以强制执行标量类型通过 int{} 初始化为零吗?