Casting boost::shared_array<void> to boost::shared_array<int>
I have some legacy code that looks like this:
void* getData(D开发者_开发技巧ataType 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 a void*
pointer to an array of int
.
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 to int*
.
Alternatively, since all your types are POD you could use an array of char
and a shared_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.
It won't work with shared_array, use shared_ptr.
boost::shared_ptr < void > getData(DataType dataType)
{
boost::shared_ptr < void > theData;
switch(dataType)
{
case TYPE_FLOAT:
theData = boost::shared_ptr<float>(new float[ rows * clms ],
boost::checked_array_deleter<float>());
break;
case TYPE_INT:
theData = boost::shared_ptr<int>(new int[ rows * clms ],
boost::checked_array_deleter<int>());
break;
case TYPE_DOUBLE:
theData = boost::shared_array<double>(new double[ rows * clms ],
boost::checked_array_deleter<double>());
break;
default:
break;
}
return theData; // I think will work
}
If that return does not work this will:
return boost::shared_ptr<void>(theData, theData.get());
精彩评论