What is the difference between static_cast and Implicit_cast?

后端 未结 4 607
小蘑菇
小蘑菇 2020-12-05 05:49

What is implicit_cast? when should I prefer implicit_cast rather than static_cast?

4条回答
  •  死守一世寂寞
    2020-12-05 06:07

    implicit_cast transforms one type to another, and can be extended by writing implicit cast functions, to cast from one type to another.

    e.g.

    int i = 100;
    long l = i;
    

    and

    int i = 100;
    long l = implicit_cast(i);
    

    are exactly the same code

    however you can provide your own implicit casts for your own types, by overloading implicit_cast like the following

    template 
    inline T implicit_cast (typename mpl::identity::type x) 
    {
        return x;
    }
    

    See here boost/implicit_cast.hpp for more

    Hope this helps

    EDIT

    This page also talks about implicit_cast New C++

    Also, the primary function of static_cast is to perform an non changing or semantic transformation from one type to another. The type changes but the values remain identical e.g.

    void *voidPtr = . . .
    int* intPtr = static_cast(voidPtr);
    

    I want to look at this void pointer, as if it was an int pointer, the pointer doesn't change, and under the covers voidPtr has exactly the same value as intPtr. An implicit_cast, the type changes but the values after the transformation can be differnet too.

提交回复
热议问题