Hi!
I\'ve used the following C macro, But in C++ it can\'t automatically cast void*
to type*
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.