C ++ use template in gettor function

Suppose there are two types of objects A and B and two getter functions

objA* getA(int id) and objB* getB(int id) 

Objects A and B are mutually exclusive. that is, if the object is A, then it is not B. When to search for the object using the identifier, the code that I use is given below. So I'm just wondering if the function can return a non-NULL pointer to an object that can point to pattern A or B. Or return null if the identifier is invalid.

 void find(int id) { objA* pa = getA(id); if (pa != NULL) { return; } objB* pb = getB(id); if (pb != NULL) { return; } } 
+4
source share
1 answer

I think Boost Variant has what you need. This is an abstraction for a single object, which can be one of several types. Then your function signature will look like this:

 boost::variant<A*, B*> find(int id); 
+3
source

All Articles