这可能对于你的示例来说有点过度,但如果你真的只需要一次存储一个数组,那么你可以使用boost::variant类和一个访问者,例如:
#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);
boost::variant<int*, char*> charVariant(cArr);
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
GetVisitor类所暗示的变量限制是,变量的所有成员都必须实现:
T operator[](int)
因此,您还可以将std::vector和std::deque作为变量的潜在成员之一添加。
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> {};
- Chris Lutz