我的代码的简化版本如下所示:
template <class T>
struct Base
{
void SayHello( T* aDerived )
{
}
void SaySomething()
{
SayHello( this ); // This is where the error happens
}
};
struct Derived : public Base< Derived >
{
};
int main(int argc, const char * argv[])
{
Derived iDerived;
iDerived.SaySomething();
}
并且它不会编译SayHello( this )
与此错误消息一致:
Cannot initialize a parameter of type 'Derived *'
with an rvalue of type 'Base<Derived> *'
现在编译器抱怨这一点是有道理的,尽管在我看来有点愚蠢,如果我删除这一行,它不会抱怨:
iDerived.SaySomething();
无论如何,这个问题可以通过显式类型转换来解决,如下所示:
SayHello( (T*)this );
问题是我的实际代码最终会出现许多这样的类型转换,在我看来,只包含在其中是合理的Base
允许它自动类型转换为其模板类的东西(T
).
是不是operator=
我追?有人可以提供代码示例来说明如何完成此操作吗?这个问题 https://stackoverflow.com/questions/5275175/using-the-type-conversion-operator建议我可以做类似的事情:
演员阵容总是介于this
and T*
.
operator T*()
{
return (T*)this;
}
但错误仍然存在。
您可以添加一个返回的辅助函数this
向下转换为派生类型
template <class T>
struct Base
{
void SayHello( T* aDerived )
{
}
void SaySomething()
{
SayHello( derived_this() );
}
private:
T* derived_this()
{
return static_cast<T*>(this);
}
您可能还想要一个const
超载:
const T* derived_this() const
{
return static_cast<const T*>(this);
}
You could添加隐式转换运算符,但我不推荐它:
operator T*() { return static_cast<T*>(this); }
隐式转换削弱了类型系统,并且可能成为错误的来源,我认为显式函数如derived_this()
更清晰、更安全。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)