How to generate compiler error on incorrect parent class?

Hi All,

I am trying to implement a reference counting scheme for memory management in this application I am writing. I have two classes: CRefCounted and CRef which look a bit like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class CRef;

class CRefCounted {
protected:
  int m_count;
public:
  CRefCounted():m_count(0) {}
  virtual ~CRefCounted() {}
  friend class CRef;
};

template <class T>
class CRef {
private:
  T* m_ptr;
public:
  ...
};


What I want is a way to generate a compiler error if CRef (my smart pointer class) is implemented for a class which is not a child of CRefCounted. Is this possible?

Any help would be greatly appreciated. Many thanks. :)
Last edited on
Maybe like this? =)
1
2
3
4
5
6
7
template <class T>
class CRef {
  private:
    CRefCounted* m_ptr;
  public:
    ...
};

I don“t know how to check, wether the class is a child of another class during compile time, but if u figure it out, You may use #error string to generate an error and stop compilation...
closed account (1yR4jE8b)
You could make CRefCounted a protected inner class inside of CRef. This way, all derived classes of CRef can see the inner class but it is only accessible outside of the class by friend functions (which you don't need to make any of, obviously).
See:
http://www.boost.org/doc/libs/1_33_1/doc/html/boost_typetraits/reference.html#boost_typetraits.is_base_of

Allows you to determine at compile time if B is a base class of D.
Thanks for the replies everyone. I think I'll try the boost 'is_base_of' when I get home tonight and report back.
Topic archived. No new replies allowed.