C->C++ Automatically cast void pointer into Type pointer in C++ in #define in case of type is not given (C-style) [MSVS]

前端 未结 4 1007
暗喜
暗喜 2021-02-15 15:00

Hi!

I\'ve used the following C macro, But in C++ it can\'t automatically cast void* to type*

4条回答
  •  不要未来只要你来
    2021-02-15 15:25

    To makes James' answer even dirtier, if you don't have decltype support you can also do this:

    template 
    class auto_cast_wrapper
    {
    public:
        template 
        friend auto_cast_wrapper auto_cast(const R& x);
    
        template 
        operator U()
        {
            return static_cast(mX);
        }
    
    private:
        auto_cast_wrapper(const T& x) :
        mX(x)
        {}
    
        auto_cast_wrapper(const auto_cast_wrapper& other) :
        mX(other.mX)
        {}
    
        // non-assignable
        auto_cast_wrapper& operator=(const auto_cast_wrapper&);
    
        const T& mX;
    };
    
    template 
    auto_cast_wrapper auto_cast(const R& x)
    {
        return auto_cast_wrapper(x);
    }
    

    Then:

    #define MALLOC_SAFE(var, size)                      \
    {                                                   \
        var = auto_cast(malloc(size));                  \
        if (!var) goto error;                           \
    }
    

    I expanded on this utility (in C++11) on my blog. Don't use it for anything but evil.

提交回复
热议问题