Reputation: 166
i want a single vector say vector<userdefined> vec
to store some values. lets say i have created two objects B and C of class A.
Now i want object B to hold integers in my vector "vec" and object C to hold double in my vector "vec"
An example to illustrate this question
B.vec.pushback(int);
C.vec.pushback(double);
Can i create a template or use any overloading function to do that?
Upvotes: 0
Views: 266
Reputation: 4637
Forgetting "why" you want to do this, you could store either int
s or double
s in the same vector by using unions.
#include <vector>
union userdefined
{
int i;
double d;
userdefined(int p) : i(p) {}
userdefined(double p) : d(p) {}
};
struct C
{
std::vector<userdefined> vec;
};
int main()
{
int i = 0;
double d = 0.0;
C A;
C B;
A.vec.emplace_back(i);
B.vec.emplace_back(d);
}
I wouldn't recommend doing this. You should try to find a solution that doesn't require storing two types in the same data structure. It's too easy to access an inactive union member.
Upvotes: 1