The use of implicit conversion operators is not recommended. In C++11 you can add the keyword explicit
not only to single argument constructors, but also to conversion operators. For C++03 code, you could use an explicitly named conversion function such as self()
or down_cast()
.
Furthermore, you seem to be using the Base
class for CRTP, i.e. to enable static polymorphism. That means that you have to know at compile-time which particular Derived
class you are calling. Therefore, you should not have to use const Base&
references in any public code, except to implement a CRTP interface.
In my projects, I have a class template enable_crtp
:
#include <type_traits>
#include <boost/static_assert.hpp>
template
<
typename Derived
>
class enable_crtp
{
public:
const Derived& self() const
{
return down_cast(*this);
}
Derived& self()
{
return down_cast(*this);
}
protected:
// disable deletion of Derived* through Base*
// enable deletion of Base* through Derived*
~enable_crtp()
{
// no-op
}
private:
// typedefs
typedef enable_crtp Base;
// cast a Base& to a Derived& (i.e. "down" the class hierarchy)
const Derived& down_cast(const Base& other) const
{
BOOST_STATIC_ASSERT((std::is_base_of<Base, Derived>::value));
return static_cast<const Derived&>(other);
}
// cast a Base& to a Derived& (i.e. "down" the class hierarchy)
Derived& down_cast(Base& other)
{
// write the non-const version in terms of the const version
// Effective C++ 3rd ed., Item 3 (p. 24-25)
return const_cast<Derived&>(down_cast(static_cast<const Base&>(other)));
}
};
This class is privately derived from by any CRTP base class ISomeClass like this:
template<typename Impl>
class ISomeClass
:
private enable_crtp<Impl>
{
public:
// interface to be implemented by derived class Impl
void fun1() const
{
self().do_fun1();
}
void fun2()
{
self().do_fun2()
}
protected:
~ISomeClass()
{}
};
The various derived classes can implement this interface in their own specific way like this:
class SomeImpl
:
public ISomeClass<SomeImpl>
{
public:
// structors etc.
private:
// implementation of interface ISomeClass
friend class ISomeClass<SomeImpl>;
void do_fun1() const
{
// whatever
}
void do_fun2()
{
// whatever
}
// data representation
// ...
};
Outside code calling fun1
of class SomeImpl
will get delegated to the appropriate const or non-const version of self()
in the class enable_crtp
and after down_casting the implementation do_fun1
will be called. With a decent compiler, all the indirections should be optimized away completely.
NOTE: the protected destructors of ISomeClass
and enable_crtp
make the code safe against users who try to delete SomeImpl*
objects through base pointers.