如何用c++判断一个类型是vector

如何用c++判断一个类型是vector

我们使用模板元编程来搞定

这里我们可以定义一个模板结构体 is_std_vector,并对其进行特化,以便专门处理 std::vector 类型。

.

下面是详细的实现和使用示例。

实现 is_std_vector 类型, 继承自false_type

首先,我们定义一个模板结构体 is_std_vector,并提供其特化版本用来处理 std::vector 类型。

cpp 复制代码
#include <type_traits>
#include <vector>

// 默认情况下,is_std_vector<T> 继承自 std::false_type
template <typename T> struct is_std_vector : false_type {};

// 特化版本,当 T 是 std::vector<T> 时,继承自 std::true_type
template<typename T> struct is_std_vector<vector<T>> : true_type {};

// 辅助变量模板,用于简化使用
template<typename T>
constexpr bool IS_VECTOR = is_std_vector<T>::value;

int main()
{
	vector<int> a = { 1, 2, 3 };
	if (IS_VECTOR<decltype(a)>)
		cout << "vector" << endl;
	else
		cout << "not vector" << endl;
	
	int b = 1;
	if (IS_VECTOR<decltype(b)>)
		cout << "vector" << endl;
	else
		cout<< "not vector" << endl;
	return 0;
}

执行结果

相关推荐
Ada's3 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python
2601_962885724 小时前
如何用 Python 计算 TRIX 三重指数平滑均线指标?
开发语言·python
还卿一钵无情泪4 小时前
Unsloth 微调 构建自己的大模型 没有GPU也能微调
linux·开发语言·人工智能·python·大模型·nlp·unsloth
倔强的石头1066 小时前
应用账号最小权限实践:读写账号、报表账号、运维账号分层
java·运维·开发语言
传人once6 小时前
页面中心圆圈放大效果如何写
开发语言·javascript·ecmascript
NeilYuen6 小时前
【C++】STL源码仿写(二):vector
开发语言·c++
蜗牛互联网7 小时前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
郝学胜_神的一滴7 小时前
游戏引擎原理与实践 04:拆解引擎基础系统与内存管理
c++·游戏
All for pursuit.7 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
weixin_307779137 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab