不推荐使用隐式转换运算符。在 C++11 中,您不仅可以将关键字 explicit 添加到单参数构造函数,还可以添加到转换运算符。对于 C++03 代码,您可以使用显式命名的转换函数,例如 self() 或 down_cast()。
此外,您似乎正在为 CRTP 使用 Base 类,即启用静态多态性。这意味着您必须在 编译时 知道您正在调用哪个特定的 Derived 类。因此,除了实现 CRTP 接口外,您不必在任何公共代码中使用 const Base& 引用。
在我的项目中,我有一个类模板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)));
}
};
此类由任何 CRTP 基类 ISomeClass 私有派生,如下所示:
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()
{}
};
各种派生类可以用自己特定的方式实现这个接口,如下所示:
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
// ...
};
调用class SomeImpl 的fun1 的外部代码将在class enable_crtp 中被委派给self() 的适当const 或非const 版本,并且在down_casting 之后将调用实现do_fun1。使用一个体面的编译器,所有的间接都应该被完全优化掉。
注意:ISomeClass 和 enable_crtp 的受保护析构函数使代码对试图通过基指针删除 SomeImpl* 对象的用户安全。