0

我在开源网络库mudu中看了一些代码,发现作者使用implicit_cat<size_t>(int)而不是static_cast<size_t>(int)在很多地方。的定义 implicit_cast如下:

// Use implicit_cast as a safe version of static_cast or const_cast
// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
// a const pointer to Foo).
// When you use implicit_cast, the compiler checks that the cast is safe.
// Such explicit implicit_casts are necessary in surprisingly many
// situations where C++ demands an exact type match instead of an
// argument type convertable to a target type.
//
// The From type can be inferred, so the preferred syntax for using
// implicit_cast is the same as for static_cast etc.:
//
//   implicit_cast<ToType>(expr)
//
// implicit_cast would have been part of the C++ standard library,
// but the proposal was submitted too late.  It will probably make
// its way into the language in the future.
template<typename To, typename From>
inline To implicit_cast(From const &f)
{
  return f;
}

我能理解评论的意思。这是一个例子:

class Top{};
class MiddleA : public Top{};
class MiddleB : public Top{};
class Bottom : public MiddleA, public MiddleB{};
void func(MiddleA const& A){
    cout << "A" << endl;
}
void func(MiddleB const& B){
    cout << "B" << endl;
}
int main(){
    Top bot;
    func(implicit_cast<MiddleA const&>(bot));  //error
    func(implicit_cast<MiddleB const&>(bot)); //error
}

当涉及到类型层次结构中的向上转换时,implicit_cast可以检测从类型 From 到类型 To 的转换是否合法,而static_cast不能检测。但为什么要使用implicit_cast<size_t>(int)而不是static_cast<size_t>(int)
我猜这有两个可能的原因:

  • implicit_cast比更有意义static_cast
  • size_t依赖于实现,因此implicit_caststatic_cast

但我不知道哪一个是真的。也许他们两个都是假的。

4

1 回答 1

2

但为什么要使用implicit_cast<size_t>(int)而不是static_cast<size_t>(int)

出于与类案例相同的原因。一般来说,原因也与不鼓励 C 风格转换的原因相同:更喜欢使用允许包含您想要的转换的最少转换集的转换,这样您就不会意外执行您不想要的转换.

于 2020-10-23T09:07:08.393 回答