可以static_assert检查类型是否为vector
Can static_assert check if a type is a vector?
static_assert可以检查类型是否为vector吗?例如,int
会引发断言,而vector<int>
不会。
我在想这样写:
static_assert(decltype(T) == std::vector, "Some error")
是。考虑以下元函数:
#include <stdio.h>
#include <vector>
template <class N>
struct is_vector { static const int value = 0; };
template <class N, class A>
struct is_vector<std::vector<N, A> > { static const int value = 1; };
int main()
{
printf("is_vector<int>: %dn", is_vector<int>::value);
printf("is_vector<vector<int> >: %dn", is_vector<std::vector<int> >::value);
}
简单地使用它作为您在static_assert
中的表达式
c++0x:
static_assert(std::is_same<T, std::vector<int>>::value, "Some Error");
通解。给定一个类型和一个模板,检查该类型是否是后者的实例:
template<typename T, template<typename...> class Tmpl>
struct is_instance_of_a_given_class_template : std:: false_type {};
template<template<typename...> class Tmpl, typename ...Args>
struct is_instance_of_a_given_class_template< Tmpl<Args...>, Tmpl > : std:: true_type {};
有了这个,那么下列语句将为真:
is_instance_of_a_given_class_template< vector<int> , vector > :: value
type to check ~~~~~~~^ ^
template to check against ~~~~~~~~~~~~~~~~~~~~~~~/
,因此你会使用:
static_assert( is_instance_of_a_given_class_template<T,std::vector>::value
, "Some error")
注意:如果T
是const
,这将不能直接工作。所以测试is_instance_of_a_given_class_template< std::decay_t<T> ,std::vector>
之类的东西。
是。
template<typename T>
struct isVector
{
typedef char (&yes)[2];
template<typename U>
static yes check(std::vector<U>*);
static char check(...);
static const bool value = (sizeof(check((T*)0)) == sizeof(yes));
};
用法:
isVector<vector<int> >::value;
isVector<int>::value;
演示。
注意:我的(复杂的)答案有一个限制,如果T
从vector<>
公开继承,它的计算结果为true
。如果T从vector<>
继承了private
/protected
,那么可能会导致编译错误。只是为了记录,这种方式不应该使用!!:)
相关文章:
- std::vector::迭代器是否可以合法地作为指针
- 是否可以将具有不同签名的 lambda 存储在 std::vector 中并在函数中执行它们(使用各自的参数)?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- vector是否为std::移动的对象连续分配内存
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- std::vector::assign/std::vector::operator=(const&) 是否保证在"this"中重用缓冲区?
- std::vector 是否有用于引用的复制构造函数?
- 递减 std::vector::begin 是否未定义,即使它从未被使用过?
- 使用 vector 检查表达式中的括号是否平衡
- 结构化绑定是否适用于 std::vector?
- 访问"std::vector"的保留但未调整大小的内存作为原始内存是否安全?
- 使用 std::vector<char> 作为异构记录的存储是否安全?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- 是否可以交换在 c++ 中作为函数 func(say) 中的参数传递的 const 向量的两个元素,例如:vector<int>func (const vector<int>&
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- 是否可以使用 std::vector<std::any> vec;这将导致异构数据类型
- 在从 std::vector 移动的上调用 .clear()、.shrink_to_fit()、.empty() 是否合
- std::vector X(0) 是否保证不分配
- 如何确定字符串是否包含在 std::vector 的任何字符串中
- 是否vector::push_back()进行浅拷贝&如何解决这个问题