so true

心怀未来,开创未来!
随笔 - 160, 文章 - 0, 评论 - 40, 引用 - 0
数据加载中……

C++ implements final keyword

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
using namespace std;
//part 1
class A {
private:
    A() {};
public:
    static A* GetInstance() {
        return new A();
    }
};
//part 2
class A {
    friend class B;
private:
    A() {};
};
class B: public A {
};
//part 3
class A {
    friend class B;
private:
    A() {};
};
class B: virtual public A {
};
//part 4: 奇异递归模板模式(curiously recurring template pattern,CRTP)
template <typename T>
class A {
    friend T;
private:
    A() {};
};
class B: virtual public A<B> {
};
//part 4.2:
//这种技术获得了类似于虚函数的效果,并避免了动态多态的代价。也有人把CRTP称为“模拟的动态绑定”
template <typename T>
struct counter
{
    static int objects_created;
    static int objects_alive;
    counter()
    {
        ++objects_created;
        ++objects_alive;
    }
    
    counter(const counter&)
    {
        ++objects_created;
        ++objects_alive;
    }
protected:
    ~counter() // objects should never be removed through pointers of this type
    {
        --objects_alive;
    }
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
    ...
};
    
class Y : counter<Y>
{
     ...
};
//part 5
class A {
protected:
    A() {};
};
class B: virtual A {
};
//part 6
class B final {
};
//validate
class C: public B {
};
int main(int argc, char* argv[]) {
    B b;
    C c;
    return 0;
}

posted on 2017-07-17 19:31 so true 阅读(165) 评论(0)  编辑  收藏 所属分类: C&C++


只有注册用户登录后才能发表评论。


网站导航: