• Advertisement
Sign in to follow this  

different types in same container

This topic is 3351 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
Quote:
Original post by sfx81
ANS: 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 this post


Link to post
Share on other sites
Quote:
Original post by sfx81

ANS: 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->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);
....
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement