Guest User

Untitled

a guest
Aug 5th, 2016
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. #include <memory>
  5.  
  6. enum ObjectType {
  7.   ObjectTypeA,
  8.   ObjectTypeB,
  9.   ObjectTypeC,
  10.   ObjectTypeD,
  11. };
  12.  
  13. class Base {
  14.  public:
  15.   Base() : x_(0) {}
  16.   virtual ~Base() {}
  17.  
  18.   virtual bool isOfType(ObjectType type) const { return false; }
  19.   virtual int slowGet(int y) { return x_ + y; }
  20.   bool isA() { return isOfType(ObjectTypeA); }
  21.   bool isB() { return isOfType(ObjectTypeB); }
  22.   bool isC() { return isOfType(ObjectTypeC); }
  23.  
  24.  protected:
  25.   int x_;
  26. };
  27.  
  28. class Zclass {
  29.   virtual void Hello() { printf("hello!\n"); }
  30. };
  31.  
  32. class A : public Base {
  33.  public:
  34.   bool isOfType(ObjectType type) const override { return type == ObjectTypeA; }
  35.   int slowGet(int y) override { return x_ - y; }
  36. };
  37.  
  38. class B : public Base {
  39.  public:
  40.   bool isOfType(ObjectType type) const override { return type == ObjectTypeB; }
  41.   int slowGet(int y) override { return x_ * y; }
  42. };
  43.  
  44. class D : public A, public Zclass {
  45.  public:
  46.   bool isOfType(ObjectType type) const override { return type == ObjectTypeD ; }
  47. };
  48.  
  49. class C final: public B {
  50.  public:
  51.   bool isOfType(ObjectType type) const override {
  52.     return type == ObjectTypeC || B::isOfType(type);
  53.   }
  54.   int slowGet(int y) override { return x_ + y - 1; }
  55. };
  56.  
  57. __attribute__((noinline)) void printBase(Base* ptr) {
  58.   printf("%d\n", ptr->isOfType(ObjectTypeB));
  59. }
  60.  
  61. __attribute__((noinline)) void printA(A* ptr) {
  62.   printf("%d\n", ptr->isOfType(ObjectTypeD));
  63. }
  64.  
  65. int main() {
  66.   std::unique_ptr<Base> ptr;
  67.   std::unique_ptr<A> ptr2;
  68.   for (int i = 0; i < 4; i++) {
  69.     switch (i) {
  70.       case 0:
  71.         ptr.reset(new A());
  72.         ptr2.reset(new A());
  73.         break;
  74.       case 1:
  75.         ptr.reset(new B());
  76.         ptr2.reset(new A());
  77.         break;
  78.       case 2:
  79.         ptr.reset(new C());
  80.         ptr2.reset(new A());
  81.         break;
  82.       case 3:
  83.         ptr.reset(new D());
  84.         ptr2.reset(new D());
  85.         break;
  86.    }
  87.    printBase(ptr.get());
  88.    printA(ptr2.get());
  89.    printf("\n");
  90.   }
  91.  
  92.   return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment