C++ (Qt)void * theNode; ..if ((size_t) theNode & 1 != 0) { // взведен младший бит - это parent нод Parent * theParent = (Parent *)((size_t) theNode & NODE_MASK); ...} else { Leaf * theLeaf = (Leaf *) theNode; // это leaf нод ..}
C++ (Qt)class A{public: void func1() {} void func2() {}}; void *addr1 = (void*)&A::func1;void *addr2 = (void*)&A::func2; if (addr1 != addr2)...elae...
C++ (Qt)#include <iostream>#include <list>#include <ctime>#include <cstdlib>#include <cstdio> using namespace std; enum type_derived { TYPE_INT, TYPE_F }; class Base{public: Base() {} virtual ~Base() {} virtual void print() = 0; virtual type_derived type() const = 0;}; class DerivedInt : public Base{public: DerivedInt(int id = 0) : m_id(id) {} void print() { /*cout << "DerivedInt, id = " << m_id << endl;*/ } type_derived type() const { return TYPE_INT; } void myFunc() { /*cout << "DerivedInt, id = " << m_id << endl;*/ } // not virtualprivate: int m_id;}; class DerivedF : public Base{public: DerivedF(float id = 0.0f) : m_id(id) {} void print() { /*cout << "DerivedF, id = " << m_id << endl;*/ } type_derived type() const { return TYPE_F; } void myFunc() { /*cout << "DerivedF, id = " << m_id << endl;*/ } // not virtualprivate: float m_id;}; typedef list<Base*> ListBase;typedef list<Base*>::iterator Iter; void generate(ListBase &l, size_t N) { for (size_t i = 0; i < N; ++i) { if (rand() % 2) l.push_back(new DerivedInt(i)); else l.push_back(new DerivedF(float(i))); }} void clearList(ListBase &l) { for (Iter it = l.begin(); it != l.end(); ++it) { delete *it; } l.clear();} void test_dynamic_cast(ListBase &l) { Iter it = l.begin(); for(; it != l.end(); ++it) { DerivedF *obj = dynamic_cast<DerivedF*>(*it); if (obj) obj->myFunc(); }} void test_virtual_fun(ListBase &l) { Iter it = l.begin(); for(; it != l.end(); ++it) { if ((*it)->type() == TYPE_F) { DerivedF *obj = static_cast<DerivedF*>(*it); obj->myFunc(); } }} int main(){ ListBase lb; size_t Num = 20000000; srand(time(0)); generate(lb, Num); clock_t tStart = clock(); test_dynamic_cast(lb); //test_virtual_fun(lb); cout << (float)(clock() - tStart) / CLOCKS_PER_SEC << endl; clearList(lb); return 0;}
C++ (Qt)typedef list<Base*> ListBase;typedef list<Base*>::iterator Iter;
C++ (Qt)void generate(ListBase &l, size_t N) { for (size_t i = 0; i < N; ++i) { if (rand() % 2) l.push_back(new DerivedInt(i)); else l.push_back(new DerivedF(float(i))); }}
C++ (Qt)void test_dynamic_cast(ListBase &l) { Iter it = l.begin(); for(; it != l.end(); ++it) { DerivedF *obj = dynamic_cast<DerivedF*>(*it); // Один вызов dynamic_cast if (obj) obj->myFunc(); // один вызов не виртуального метода! }} void test_virtual_fun(ListBase &l) { Iter it = l.begin(); for(; it != l.end(); ++it) { if ((*it)->type() == TYPE_F) { // Один вызов виртуального метода DerivedF *obj = static_cast<DerivedF*>(*it); // Пренебрегаем издержками на вызов static_cast obj->myFunc(); // один вызов не виртуального метода! } }}