Reputation: 811
I have briefly looked around various c++ sites and text books. But none of them have had anything related to what I was looking for.
What I want is a list in c++ which can contain int, string and int array variables within it. But before I spend hours playing around with some code, I was wondering if anyone knew if such a thing actually exists? I'm not asking for code to be shown to me, if it is possible, I will attempt it, and then ask about any issues I have with it.
Thanks
Upvotes: 0
Views: 106
Reputation: 1774
In case you meant an object that can contain int, string and arrays as separate objects, not as one (like union) -- I think you should take a look at C++11 tuples , and use them in list.
Upvotes: 2
Reputation: 1539
You can also create a struct using union or void pointer.
enum varType
{
vt_int,
vt_float,
vt_string
}
class myVariant
{
private:
void* mVariable;
varType mType;
};
or also,
class myVariant2
{
private:
union
{
float fValue;
int iValue;
std::string* sValue;
};
varType mType;
}
It's not nice and would require casting heavily, but if you don't like using other libraries for such small task, this might be of help.
Edit1: You will need getStringValue, getFloatValue getIntValue functions.
Edit2: You can safely use this classes in std::list.
Edit3: You need to call destructor of std::string (if the variable is a string) yourself.
Upvotes: 0
Reputation: 16
It might be unsafe to put different types of objects/data in single list.
But if it the requirement, then why not derive new class from std::list with combination of keeping track of types being inserted into list using aproach mentioned in above answer.
Upvotes: 0
Reputation: 8866
Your best bet is boost::variant. Remember - I didn't tell you it will be easy.
Usage will be simple:
typedef boost::variant<...my necessary types...> MyVariant;
std::list<MyVariant> myList;
Upvotes: 5