判断类中是否有虚函数

#include<iostream>
#include<string>
#include <stack>
using namespace std;

#include <iostream>
#include <type_traits>

template<typename T>
struct HasVirtual : public T
{
    bool hasVirtualFlag;
    bool operator() () const  {
        return (int64_t)(reinterpret_cast<void*>(const_cast<bool*>(&this->hasVirtualFlag))) == 
        (int64_t)reinterpret_cast<void*>(const_cast<HasVirtual<T>*>(this)) + sizeof(T);
    }
};

class A {
public:
    bool first_member;
    virtual void func() {};
    ~A() {}  // A 有虚析构函数
};

class B {
public:
    bool first_member;
    ~B() {}  // B 没有虚析构函数
};

int main() {
    // B b; A a;
    // std::cout << "A" <<  (int64_t(reinterpret_cast<void*>(&a)) == int64_t(reinterpret_cast<void*>(&a.first_member))) << endl ;
    // std::cout << "A" <<  (int64_t(reinterpret_cast<void*>(&b)) == int64_t(reinterpret_cast<void*>(&b.first_member)))  << endl; ;
    HasVirtual<A>   a;
    HasVirtual<B>   b;
    cout << "A" << a() << endl;
    cout << "B" << b() << endl;
    return 0;
}

 

posted @ 2024-07-26 16:04  yushimeng  阅读(1)  评论(0编辑  收藏  举报