I have some legacy C code which I've wrapped with a C++ interface for new C++ code to use. The C code used void* to load data from a file. It knew how much data to load internally based on the enum tag you'd send in:
bool load_data( TAG_TYPE tag, void* data );
My C++ wrapper looks something like:
template<typename T>
T load( TAG_TYPE tag ) {
T data;
bool success = load_data( tag, &data );
assert( success );
return data;
}
This adds some type safety and is cleaner for C++ code. And we can use auto & const:
const auto foo = load<int>( TAG_NUM_POINTS );
Now someone needs to load an array from the file. They'd like to use std::array because this is C++.
const auto foo = load<std::array<int, 3>>( TAG_RGB_VALUE );
Is this safe? It seems to compile and run fine. Under the covers it will pass &std::array<int, 3>
as the data
value, instead of the preferred data.data()
.
It seems like this is an area where I'd want to do template specialization, but then I'd need to add template parameters for the type and size of the std::array? Is that possible, and is it the way to go?