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

执行结果

相关推荐
IT阳晨。17 分钟前
【QT开发】交叉编译QT程序在ARMLinux平台上运行
c++·qt·交叉编译·armlinux·代码移植
CoderYanger26 分钟前
前端基础——CSS练习项目:百度热榜实现
开发语言·前端·css·百度·html·1024程序员节
派大星爱吃猫40 分钟前
C++隐藏的this指针(详解)
c++·this指针
虾..1 小时前
C++ 哈希
开发语言·c++·哈希算法
liu****1 小时前
14.日志封装和线程池封装
linux·开发语言·c++
青青草原羊村懒大王1 小时前
python基础知识三
开发语言·python
将编程培养成爱好1 小时前
C++ 设计模式《统计辅助功能》
开发语言·c++·设计模式·访问者模式
fie88891 小时前
基于循环谱分析的盲源分离信号处理MATLAB
开发语言·matlab·信号处理
kgduu1 小时前
go-ethereum之rpc
开发语言·rpc·golang
yong99902 小时前
MATLAB倍频转换效率分析与最佳匹配角模拟
开发语言·前端·matlab