Reputation: 390
I have read some code in muduo, an open source network library, and I found that the author use implicit_cat<size_t>(int)
rather than static_cast<size_t>(int)
in many place. The definition of implicit_cast
is as follows:
// 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;
}
I can understand what the comment means. Here is a example:
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
}
When it comes to upcasting in the type hierarchy, the implicit_cast
can detect whether the cast from the tyep From to the type To is legitimate while the static_cast
cannot. But why use implicit_cast<size_t>(int)
instead of static_cast<size_t>(int)
?
There are two possible reasons I guess for this:
implicit_cast
is more meaningful than static_cast
size_t
is implementation-dependent, so implicit_cast
is safer than static_cast
But I don't know which one is true. Maybe both of them are false. 😅
Upvotes: 0
Views: 530
Reputation: 238461
But why use
implicit_cast<size_t>(int)
instead ofstatic_cast<size_t>(int)
?
For the same reason as in the class case. In general, the reason is also the same as why C style casts are discouraged: Prefer using the cast which allows minimal set of casts that contains the cast that you want so that you don't accidentally perform a cast that you don't want.
Upvotes: 2