如何用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;
}

执行结果

相关推荐
尘中远16 小时前
Qt高性能绘图库QIm——实现二维三维科学绘图
开发语言·qt·信息可视化
雨辰AI16 小时前
从零搭建大模型本地运行环境|Python+CUDA 基础配置避坑大全
大数据·开发语言·人工智能·python·ai·ai编程·ai写作
h_a_o777oah16 小时前
【算法专项】扩展域并查集:原理详解及解决大部分种类并查集问题(洛谷P5937 P2024 C++代码)
数据结构·c++·算法·acm·并查集·扩展域·逻辑建模
DogDaoDao16 小时前
【第 05 篇】Python的字典与集合
开发语言·python·集合·字典
兰令水16 小时前
leecodecode【单调栈】【2026.6.12打卡-java版本】
java·开发语言·算法
leagsoft_100316 小时前
零信任选型五刀法——零信任怎么选?五个问题,五条红线
开发语言·php
AI人工智能+电脑小能手17 小时前
【大白话说Java面试题 第112题】【并发篇】第12题:AQS 中节点的入队时机有哪些?
java·开发语言·面试
IT WorryFree17 小时前
Zabbix 7.4 API 可同步全量参数清单(同步第三方系统专用)
java·开发语言·zabbix
码云骑士17 小时前
06-Python装饰器从入门到源码(上)-闭包与自由变量
开发语言·python
码云骑士17 小时前
10-Python运行时内存模型-栈帧-堆-引用计数-GC分代回收的全景图
开发语言·python