c – 使用static_cast实现的转换运算符

前端之家收集整理的这篇文章主要介绍了c – 使用static_cast实现的转换运算符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我提出 here问题之后,我问这个问题.

关键很简单.假设你有两类这样的类:

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节),但由于我缺乏经验,我无法找到答案.

我非常感谢任何人花时间帮我解决这个问题.

解决方法

查看n3337中的[expr.static.cast](标准后的第一份工作草案):

2/ An lvalue of type “cv1 B,” where B is a class type,can be cast to type “reference to cv2 D,” where D is a class derived (Clause 10) from B,if a valid standard conversion from “pointer to D” to “pointer to B” exists […]

4/ Otherwise,an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed,for some invented temporary variable t [..]

因此,我会解释gcc的行为是正确的,即表达式:

static_cast<Derived const&>(*this)

不应该以递归方式调用运算符Derived const& ()const.

我从存在的关键字中推断出这一点,这意味着规则的排序.规则2 /应在规则4 /之前进行.

原文链接:https://www.f2er.com/c/118618.html

猜你在找的C&C++相关文章