'Generate std::array types and store them for runtime use
I have a wrapper class which is templated on the container type I am using, which may be an std::array of some size:
//! @tparam C the random access container type to be wrapped. E.g.
//! std::vector, or std::array.
template<class C>
class MyWrapper
{
public:
...
//! @return the maximum number of elements that can be stored by the wrapped
//! container.
static size_t cardinality();
}
Now, I can create this wrapper using an std::array at compile time. All good so far. The problem is that this wrapper will then be sent to another module over the network( serialized using protobuf and grpc). Now, I can send the type of the container, size and the data it carries. For instance, if I have an object of type Wrapper<std::array<double, 6>>, I can send the information about this being a wrapper for an std::array, of size six, which carries doubles.
The problem is that on the receiver side, I have to re-create the exact same object. But I cannot have e.g. a function that takes a size and type argument and creates an array at run time, e.g.
template<class T>
createArr(size_t n)
{
MyWrapper<std::array<T, n>> arr;
...
}
Thus, my idea is that I should be able to generate some std::array types at compile time, store them in a lookup table and use this table to create arrays at runtime. This will have the constraints that I will only be able to support a limited number of types and sizes, e.g.:
std::array<int, 1>
std::array<int, 2>
...
std::array<int, 1000>
std::array<double, 1>
std::array<double, 2>
...
std::array<double, 1000>
but I am okay with that.
Is there any way of doing this, e.g. using template metaprogramming?
EDIT: If I do something like this:
template<class T, int n>
createArr()
{
MyWrapper<std::array<T, n>> arr;
...
}
This means that I will have to have a template declaration for each type and size, something I want to avoid writing out plainly in the code, since I have so many types and sizes...that's why I thought it would be possible to generate these somehow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
