对于您的示例来说,这可能有点矫枉过正,但如果您真的一次只需要存储一个数组,那么您可以使用 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); //- 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
GetVisitor 类隐含的对变体的限制是变体的所有成员都必须实现:
T operator[](int)
因此,您还可以添加例如 std::vector 和 std::deque 作为变体的潜在成员。