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

执行结果

相关推荐
Mr_Xuhhh1 天前
YAML相关
开发语言·python
阿巴~阿巴~1 天前
JsonCpp:C++ JSON处理利器
linux·网络·c++·json·tcp·序列化和反序列化
咖啡の猫1 天前
Python中的变量与数据类型
开发语言·python
前端达人1 天前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
汤姆yu1 天前
基于springboot的电子政务服务管理系统
开发语言·python
全栈师1 天前
C#中控制权限的逻辑写法
开发语言·c#
S***q1921 天前
Rust在系统工具中的内存安全给代码上了三道保险锁。但正是这种“编译期的严苛”,换来了运行时的安心。比如这段代码:
开发语言·后端·rust
打点计时器1 天前
matlab 解决wfdb工具使用本地数据集报错
开发语言·matlab
zmzb01031 天前
C++课后习题训练记录Day38
开发语言·c++
獭.獭.1 天前
C++ -- STL【string的使用】
c++·string·auto