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

执行结果

相关推荐
Coding小公仔1 小时前
C++ bitset 模板类
开发语言·c++
菜鸟看点2 小时前
自定义Cereal XML输出容器节点
c++·qt
小赖同学啊2 小时前
物联网数据安全区块链服务
开发语言·python·区块链
shimly1234562 小时前
bash 脚本比较 100 个程序运行时间,精确到毫秒,脚本
开发语言·chrome·bash
IT_10242 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
new_zhou3 小时前
Windows qt打包编译好的程序
开发语言·windows·qt·打包程序
ye903 小时前
银河麒麟V10服务器版 + openGuass + JDK +Tomcat
java·开发语言·tomcat
武昌库里写JAVA3 小时前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计
悲伤小伞3 小时前
linux_git的使用
linux·c语言·c++·git