我在开源网络库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_cast
比static_cast
但我不知道哪一个是真的。也许他们两个都是假的。