I'm trying to write a smart pointer wrapper (contains a boost shared_ptr or scoped_ptr or another smart pointer wrapper); each wrapper type injects a bit of extra functionality (eg. logging usage, lazy init, verifying correct construction/destruction order, etc) but I want them to be as invisible as possible to the user (such that I could swap in/out wrappers simply by changing a single typedef, and possibly some constructor code, but none of the usage code).
Normal usage is trivial:
template<typename T>
class some_smart_ptr_wrapper
{
public:
typedef typename T::value_type value_type;
...
value_type* get() { /*do something magic*/ return m_ptr.get(); }
const value_type* get() const { /*do something magic*/ return m_ptr.get(); }
// repeat for operator->, operator*, and other desired methods
private:
T m_ptr;
};
typedef some_smart_ptr_wrapper< boost::shared_ptr<int> > smart_int;
smart_int p;
(Now all other code can use p
indistinguishably from a shared_ptr, at least for the defined operations, and I can add extra wrappers just by changing the typedef.)
Multiple wrappers can be used simultaneously simply by nesting them as you'd expect, and only the code that declares (and sometimes initialises) the variable needs to care.
Occasionally though it's useful to be able to get the "basic" shared/scoped_ptr from a wrapper (particularly to pass a shared_ptr as an argument to a function that doesn't need to trigger the functionality added by the wrappers); for a single wrapper layer it's easy:
T& getPtr() { return m_ptr; }
const T& getPtr() const { return m_ptr; }
But this doesn't scale nicely to multiple wrapper layers (the caller has to do p.getPtr().getPtr().getPtr()
the correct number of times).
What I'd like to be able to do is to declare getPtr() such that:
- if T implements getPtr(), then it returns m_ptr.getPtr() (whatever type that is).
- if T does not implement getPtr(), then it returns m_ptr.
- it's still available in both const and non-const flavours, as you'd expect.
The net result of which is that a single call to getPtr() from the outside code will "walk up" the chain to the original smart pointer, since that will be the only one that doesn't implement getPtr().
I'm fairly sure that the solution will involve SFINAE and boost::enable_if; I've had a bit of a play towards trying to get something like that to work but haven't had much luck thus far.
Solutions or completely alternate approaches both welcomed; note that I would like it to work in both VC++2008 and GCC (ie. no C++11, sadly).