yodahaji
yodahaji

Reputation: 877

How can I implement a data structure support different types element just like an array in C++?

just like an array means this data structure support return the element of certain index in O(1) times.different types mean both builtin type and user defined class which should use reference.

for example, A is the class which have made this structure down. The b,c is instance of different classes. And the A should support follow operate:

A a(10);//apply for storage of 10 elements

a[0]=120;

a[1]=’a’;

a[2]=”adsad”;

a[3]=b;

a[3]=c;

a[1]=c;

a[2]=123.5;

…

this question is not for the practical use, just for the curiosity.

now I have known how can solve this. it is really cool:D

Upvotes: 2

Views: 131

Answers (1)

AMA
AMA

Reputation: 4214

You could do that with an std::vector or an std::array of std::any.

Like the following:

std::vector<std::any> many_any(10);
many_any[0] = 120;
many_any[1] = 'a';
many_any[2] = std::string("adsad");
many_any[3] = 123.5;

std::cout << std::any_cast<int>(many_any[0]) << std::endl;
std::cout << std::any_cast<char>(many_any[1]) << std::endl;
std::cout << std::any_cast<std::string>(many_any[2]) << std::endl;
std::cout << std::any_cast<double>(many_any[3]) << std::endl;

This code outputs:

 120
 a
 adsad
 123.5

And here is a live-example.


std::any is a heterogeneous container that uses type-erasure to store any type. It is a part of C++17 standard. Here is a series of articles that explains how type-erasure could be implemented in C++: Type erasure — Part I.

Important Note: You should consider very carefully if you really need std::any. As it is more of a "yes, we can!" feature, which is rarely useful in the pure form. Other options include storing objects in a polymorphic setting: either using interfaces (which can also be implemented using type-erasure) or variant+visitor.

Update: if your compiler does not support C++17 you can take a look at Boost's any implementation.

Upvotes: 4

Related Questions