This is probably overkill for your example, but if you really only need to store one array at a time, then you can use the boost::variant class and a visitor, e.g.,
#include <boost/variant.hpp>
#include <iostream>
template< typename T >
class GetVisitor : public boost::static_visitor<T>
{
public:
GetVisitor(int index) : index_(index) {};
template <typename U >
T operator() (U const& vOperand) const
{
return vOperand[index_];
}
private:
int index_;
};
int main ()
{
int iArr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
char cArr[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
boost::variant<int*, char*> intVariant(iArr); //- assign integer array to variant
boost::variant<int*, char*> charVariant(cArr); //- assign character array to another variant
int testInt = boost::apply_visitor(GetVisitor<int>(2), intVariant);
char testChar = boost::apply_visitor(GetVisitor<char>(9), charVariant);
std::cout << "returned integer is " << testInt << std::endl;
std::cout << "returned character is " << testChar << std::endl;
return 0;
}
output is:
returned integer is 3
returned character is j
The restriction on the variant implied by the GetVisitor class is that all members of the variant must implement:
T operator[](int)
So you could also add, e.g., std::vector and std::deque as potential members of the variant.
template <typename T> struct helper { T arr[10]; T get(std::size_t i) { return arr[i]; } }; struct foo : public helper<int>, public helper<char> {};
– Colum