Reputation: 708
I am having to add new functionality to some old, poorly written code. There are 50 different lists which need to be displayed and processed on screens, and the current code for them is all cut-and-paste with minor modifications from 2 different types, one a list in a DAO database and the other in a map.
I wrote a Search class which provides the functionality, and a helper class for each of the list types to provide the basic functions needed by Search. The map helper class only requires access to the tstring Key, it does not need the differentObject Values. But, I can't get this to compile.
Since the various differentObjects have no relationship, I defined a class SearchValue which is basically empty, and added it in the .h as a superclass for all the differentObject classes.
As an example, here is one of the map definitions:
typedef map<tstring, MyPatListEntry *, tstringcomp> patlist;
MyPatListEntry is defined:
class MyPatListEntry : public SearchValue {
and I have the function defined as:
ListHelper(map<tstring, SearchValue *> *map, CString fieldName)
The compiler (VC++) gives the error that none of the definitions for ListHelper() handles all the arguments. If I replace SearchValue with MyPatListEntry in the definition the compilation works, so the basic format is correct.
I've looked around on the site and found people suggesting this type of thing be done with function templates, and I suppose that would work, but I am curious whether there is some reason doing it this way does not work.
Thanks for any thoughts.
Upvotes: 1
Views: 1367
Reputation: 121
If you really need ListHelper to have different behavior over different SearchValue types, it may be appropriate to template the function over the value type of your map:
template <class AnySearchValue> ListHelper(map<tstring, AnySearchValue *> *map, CString fieldName)
It's hard to say if that's workable without seeing more of the implementation though. (oops sorry, missed in your OP where you said you'd considered this)
Upvotes: 0
Reputation: 1941
What you are asking for is called covariant generic type parameters in C# world (not possible in C++) and even there it would not work in your situation. The reason is actually quite straightforward.
Imagine the following code:
class B {};
class D1 : public B {};
class D2 : public B {};
map<string, D1 *> myMap;
D2 someObject;
void myFunc(map<string, B *> & someMap)
{
someMap["foo"] = &someObject;
}
You are not allowed to call myFunc
with myMap
as a parameter because of this problem. You would be allowed to assign someObject
of type D2
into a map that is supposed to contain D1
.
Upvotes: 3