#include <iostream>
#include <memory>
// 智能指针作为模板参数,并判断该智能指针管理的类型是否为指定类的子类
struct Base{};
struct Derived: Base{
};
struct Derived1{
};
// 使用enable_if和is_base_of结合判断,T::element_type为智能指针所管理的对象类型,需要加typename
template <typename T, typename = std::enable_if_t<std::is_base_of_v<Base,typename T::element_type>>>
void Convert(T elem){
std::cout<<"T is subClass of Base"<<std::endl;
}
// 利用static_assert
template <typename T>
void Convert_Assert(T elem){
static_assert(std::is_base_of_v<Base, typename T::element_type>, "T is not subClass of Base");
std::cout<<"T is subClass of Base"<<std::endl;
}
int main(){
std::shared_ptr<Derived> son = std::make_shared<Derived>();
Convert(son);
Convert_Assert(son);
std::shared_ptr<Derived1> notSon = std::make_shared<Derived1>();
// Convert(notSon); error
// Convert_Assert(notSon); error
return 0;
}
智能指针作为模板参数并校验是否子类
最新推荐文章于 2024-04-03 20:11:39 发布
这篇博客展示了如何利用C++的模板和`std::enable_if`以及`std::is_base_of`来检查智能指针管理的对象是否为特定基类的子类。通过`Convert`和`Convert_Assert`两个函数,分别展示了条件编译和`static_assert`的用法,以确保类型检查在编译时期进行。
711

被折叠的 条评论
为什么被折叠?



