# different types in same container

## Recommended Posts

sfx81    131
Hi. I was wondering is its possible to have a single array/container which can contain different types. e.g my array[]= { 1,'c', "string", customObject }; Regards

##### Share on other sites
popsoftheyear    2194
Advice: When asking questions like this, mention the language you are referring to. Otherwise, you're likely to get responses like "Well yeah, of course you can", which might be true for javascript, when you were actually talking about C++, where it isn't so true (well not naturally. But you could use a variant). Or whatever. I'm not even sure if javascript can do that, but you get my point.

So... what language?

Cheers
-Scott

##### Share on other sites
Antheus    2409
Yes, it's possible. But why would you want that?

Consider this: foo[17] returns something. What are you going to do with it? How will you know it's customObject and not a bool?

##### Share on other sites
sfx81    131
thanks every one for quick replies.
we are talking C++.

"foo[17] returns something. What are you going to do with it? How will you know it's customObject and not a bool?"
ANS: we can have a header for each object (say an enum) which tells what object it is, isnt it ?

I think varient is something I am after.
Cheers

##### Share on other sites
Telastyn    3777
Quote:
 Original post by sfx81ANS: we can have a header for each object (say an enum) which tells what object it is, isnt it ?

Which defeats the entire purpose of using a statically typed language.

##### Share on other sites
Antheus    2409
Quote:
 Original post by sfx81ANS: we can have a header for each object (say an enum) which tells what object it is, isnt it ?

This would typically be solved via polymorphism. Base class defines operations that can be performed on a type.
struct Base {  virtual void print() = 0;};struct IntValue : Base {  virtual void print() {    std::cout << value;  }  int value;};std::vector< Base* > values;for (int i = 0; i < values.size(); i++) {  values[i]->print();}

Quote:
 I think varient is something I am after.

Variant accomplishes the same as above, but instead of letting types define their own implementation of operations, visitor needs to know about all types. So visitor looks something like this:
struct Visitor {  void print(int i);  void print(std::string s);  void print(foo f);  ....};