C++ 为什么使用隐式_cast<;尺寸&u t>;(int)而不是静态_cast<;尺寸&u t>;(国际)?

C++ 为什么使用隐式_cast<;尺寸&u t>;(int)而不是静态_cast<;尺寸&u t>;(国际)?,c++,boost,boost-implicit-cast,C++,Boost,Boost Implicit Cast,我阅读了开源网络库muduo中的一些代码,发现作者在很多地方使用了隐式(int)而不是静态(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 cas

我阅读了开源网络库muduo中的一些代码,发现作者在很多地方使用了
隐式(int)
而不是
静态(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;
}
//使用隐式\u cast作为静态\u cast或常量\u cast的安全版本
//用于在类型层次结构中向上转换(即,转换指向Foo的指针
//指向超类Foo的指针或将指向Foo的指针强制转换为
//指向Foo的常量指针)。
//使用隐式转换时,编译器会检查转换是否安全。
//这种显式-隐式类型转换在许多情况下都是必要的
/或者C++需要精确类型匹配而不是
//可转换为目标类型的参数类型。
//
//可以推断From类型,因此使用
//隐式\u转换与静态\u转换等相同:
//
//隐式转换(expr)
//
//IyPyType将成为C++标准库的一部分,
//但提案提交得太晚了。这很可能会让你
//它将在未来进入语言。
模板
内联到隐式转换(从常量和f)
{
返回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
}
class-Top{};
A类:公共顶级{};
B类:公共顶层{};
类底部:公共MiddleA,公共MiddleB{};
无效函数(MiddleA const&A){
库特
但是为什么要使用
隐式转换(int)
而不是
静态转换(int)

原因与类案例中的原因相同。一般来说,原因也与不鼓励使用C样式转换的原因相同:更喜欢使用允许包含所需转换的最小转换集的转换,以便不会意外执行不需要的转换

但是为什么要使用
隐式转换(int)
而不是
静态转换(int)


原因与类案例中的原因相同。一般来说,原因也与不鼓励使用C样式强制转换的原因相同:更喜欢使用允许包含您想要的强制转换的最小强制转换集的强制转换,这样您就不会意外地执行您不想要的强制转换。

谢谢您的回答,但我无法理解您的观点。这将e如果你能给我一个例子就更好了谢谢你的回答,但我不能理解你的意思。如果你能给我一个例子就更好了我非常怀疑这个东西是否会进入标准,至少不是用这个名字。强制转换从来都不是隐式的。强制转换是你在源代码中编写的东西,用来告诉编译器做一个con版本。转换可以是隐式的,也可以是显式的。我很怀疑这个东西是否会进入标准,至少不会使用这个名称。强制转换从来都不是隐式的。强制转换是在源代码中编写的,用来告诉编译器进行转换。转换可以是隐式的,也可以是显式的。