C++新经典模板与泛型编程:用成员函数重载实现is_base_of
用成员函数重载实现is_base_of
std::is_base_of
是一个C++ 11
标准中用于判断某个类是否是另一个类父类的类模板。
#include "killCmake.h"
#include<string>
using namespace std;
class A
{
};
class B : public A
{
public:
B(int x): x_(x)
{}
private:
int x_;
};
//template<typename Base,typename Derived>
//struct is_base_of {...};
int main()
{
std::cout << std::is_base_of<A, A>::value << std::endl;
std::cout << std::is_base_of<B, A>::value << std::endl;
std::cout << std::is_base_of<A, B>::value << std::endl;
return 0;
}
C++ 17
标准中又引入了变量模板简化std::is_base_of
的书写。
#include "killCmake.h"
#include<string>
using namespace std;
class A
{
};
class B : public A
{
public:
B(int x): x_(x)
{}
private:
int x_;
};
//template<typename Base,typename Derived>
//struct is_base_of {...};
template<class Base,class Derived>
inline constexpr bool is_base_of_v_v = std::is_base_of<Base, Derived>::value;
int main()
{
std::cout << std::is_base_of<A, A>::value << std::endl;
std::cout << std::is_base_of<B, A>::value << std::endl;
std::cout << std::is_base_of<A, B>::value << std::endl;
std::cout << std::endl;
// 简化版本
std::cout << is_base_of_v_v<A, A> << std::endl;
std::cout << is_base_of_v_v<B, A> << std::endl;
std::cout << is_base_of_v_v<A, B> << std::endl;
return 0;
}
std::is_base_of
的实现代码,写一个IsBaseOf类模板
来实现,代码如下。
#include "killCmake.h"
#include<string>
using namespace std;
class A
{
};
class B : public A
{
public:
B(int x): x_(x)
{}
private:
int x_;
};
//template<typename Base,typename Derived>
//struct is_base_of {...};
template<class Base,class Derived>
inline constexpr bool is_base_of_v_v = std::is_base_of<Base, Derived>::value;
template<typename Base,typename Derived> // <父类,子类>
class IsBaseOf
{
private:
template<typename T>
static std::true_type test(T*);
template<typename>
static std::false_type test(void*);
template<typename B,typename D>
static auto test_middle() -> decltype(test<B>(static_cast<D*>(nullptr)));
// 调用test()
public:
static constexpr bool value = IsSameType < std::integral_constant<bool, std::is_class_v<Base>&& std::is_class_v<Derived>&& decltype(test_middle<Base, Derived>())::value
, std::integral_constant<bool, true>>::value;
};
int main()
{
std::cout << std::is_base_of<A, A>::value << std::endl;
std::cout << std::is_base_of<B, A>::value << std::endl;
std::cout << std::is_base_of<A, B>::value << std::endl;
std::cout << std::endl;
// 简化版本
std::cout << is_base_of_v_v<A, A> << std::endl;
std::cout << is_base_of_v_v<B, A> << std::endl;
std::cout << is_base_of_v_v<A, B> << std::endl;
return 0;
}
未完待续,干他菊花就对了