I have some legacy code that looks like this:
void* getData(DataType dataType)
{
switch(dataType)
{
case TYPE_FLOAT:
return new float[ rows * clms ];
case TYPE_INT:
return new int[ rows * clms ];
case TYPE_DOUBLE:
return new double[ rows * clms ];
default:
return NULL;
}
}
I’d like to be able to do this:
boost::shared_array < void > getData(DataType dataType)
{
boost::shared_array < void > theData;
switch(dataType)
{
case TYPE_FLOAT:
theData = boost::shared_array<float>(new float[ rows * clms ]);
break;
case TYPE_INT:
theData = boost::shared_array<int>(new int[ rows * clms ]);
break;
case TYPE_DOUBLE:
theData = boost::shared_array<double>(new double[ rows * clms ]);
break;
default:
break;
}
return theData;
}
But I can’t get the casting right. What do I need to do to get this statement working?
You can’t just convert, because
shared_array<void>doesn’t know how to delete avoid*pointer to an array ofint.You could try something like
shared_array<void>(new int[rows*clmns], checked_array_deleter<int>()), although I haven’t tested that it’s right. You probably need to wrap the deleter in something that converts the parameter toint*.Alternatively, since all your types are POD you could use an array of
charand ashared_array<char>. Then there’s no need to specify a deleter.Btw, insert usual grumble here about this being a dodgy design. If you’re referring to things by
void*, or void smart pointers, then you’re ignoring that C++ is a static-typed language for a reason. You might look at Boost.Variant, depending how your array is used.