-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpolyBase.h
86 lines (74 loc) · 2.16 KB
/
polyBase.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
@copyright Russell Standish 2000-2013
@author Russell Standish
This file is part of Classdesc
Open source licensed under the MIT license. See LICENSE for details.
*/
#ifndef CLASSDESC_POLYBASE_H
#define CLASSDESC_POLYBASE_H
#include <classdesc.h>
namespace classdesc
{
/// used for metaprogrammatically distinguishing between polymorphic
/// and non-polymorphic types
struct PolyBaseMarker {};
/// base class for polymorphic types. T is a type enumerator class
template <class T>
struct PolyBase: public PolyBaseMarker
{
typedef T Type;
virtual Type type() const=0;
virtual PolyBase* clone() const=0;
#if defined(__cplusplus) && __cplusplus>=201103L
typedef std::unique_ptr<PolyBase> AutoPtr;
#else
typedef std::auto_ptr<PolyBase> AutoPtr;
#endif
/// cloneT is more user friendly way of getting clone to return the
/// correct type. Returns NULL if \a U is invalid
template <class U>
U* cloneT() const {
AutoPtr p(clone());
U* t=dynamic_cast<U*>(p.get());
if (t)
p.release();
return t;
}
virtual ~PolyBase() {}
};
/// utility class for building the derived types in a polymorphic
/// heirarchy. \a Base is the base of the heirarchy.
/**
A possible use is as follows:
class MyBase: public PolyBase<int>
{
static MyBase* create(int); // factory method
};
template <int t>
class MyClass: public Poly<MyClass, MyBase>
{
public:
int type() const {return t;}
};
// see also \c Factory class for another way of doing this
static MyBase* MyBase::create(int t)
{
switch (t)
{
case 0: return new MyClass<0>;
case 1: return new MyClass<1>;
case 2: return new MyClass<2>;
default:
throw std::runtime_error("unknown class construction requested");
}
}
See also descriptor specific poly classes, such as polypack.h
*/
template <class T, class Base>
struct Poly: virtual public Base
{
/// clone has to return a Poly* to satisfy covariance
Poly* clone() const {return new T(*static_cast<const T*>(this));}
};
}
#endif