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

执行结果

相关推荐
感哥6 小时前
C++ 多态
c++
沐怡旸12 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41616 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥18 小时前
C++ std::set
c++
侃侃_天下19 小时前
最终的信号类
开发语言·c++·算法
博笙困了19 小时前
AcWing学习——差分
c++·算法
echoarts19 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix19 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
青草地溪水旁19 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁19 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式