Reputation: 1479
Suppose there are two types of object A and B and two getter functions
objA* getA(int id) and objB* getB(int id)
Object A and B are mutually exclusive. i.e. if a object is A, then it is not B. When to find a object using an ID, the code I use is below. So I am just wondering if the function can return non-NULL object pointer which may point to A or B using template. Or return null if the id is invalid.
void find(int id)
{
objA* pa = getA(id);
if (pa != NULL)
{
return;
}
objB* pb = getB(id);
if (pb != NULL)
{
return;
}
}
Upvotes: 4
Views: 93
Reputation: 35188
I think Boost Variant has what you need. It's an abstraction for a single object that might be one of several types. Your function signature then becomes:
boost::variant<A*, B*> find(int id);
Upvotes: 3