关键很简单.假设你有两类这样的类:
template < class Derived > class Base { ... operator const Derived&() const { return static_cast< const Derived& >(*this); } ... }; class Specialization : public Base<Specialization> { ... };
然后假设您有类似这样的类型转换:
template < class T > functionCall( const Base<T>& param) { const T & val(param); ... }
问题是:这种转换的标准符合行为应该是什么?
它应该与const T& val(static_cast< const T&>(param))还是应该递归迭代直到堆栈溢出?请注意,我获得了第一个用GNU g编译的行为,第二个用Intel icpc编译.
我已经试图查看标准(关于static_cast的第5.9节和关于转换的第12.3节),但由于我缺乏经验,我无法找到答案.
我非常感谢任何人花时间帮我解决这个问题.
解决方法
2/ An lvalue of type “cv1
B
,” whereB
is a class type,can be cast to type “reference to cv2D
,” whereD
is a class derived (Clause 10) fromB
,if a valid standard conversion from “pointer toD
” to “pointer toB
” exists […]4/ Otherwise,an expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed,for some invented temporary variablet
[..]
因此,我会解释gcc的行为是正确的,即表达式:
static_cast<Derived const&>(*this)
不应该以递归方式调用运算符Derived const& ()const.
我从存在的关键字中推断出这一点,这意味着规则的排序.规则2 /应在规则4 /之前进行.