-1

I have a function template to print a map of string with object pointers:

//template function to print map of pointers
template <class T2>
void printMap(std::map<string, T2*>&_map)
{
    //test print line
    cout << "Test function template for map print" << endl;
    std::map<string, T2*>::iterator iter;
    for (iter = _map.begin(); iter != _map.end(); iter++)
    {
        //call print function for type
        iter->second->print();
    }
}

I am trying to implement it:

printMap<myObject>(std::map<string, myObject*>&myMapOfObjects);

I am getting

"error type name is not allowed"

I am also getting an error on the linux server that a ; is expected before iter and that iter is undeclared.

I have tested the files with a basic function template and the functions are being passed to the file, it's just the way I written this function, it's not happy with what I am doing. I have been working on this for a few days now and am unable to find the solution, I am sure it is obvious to experienced programmers, thanks.

Another question: can I pass string as a separate type, so have T1 and T2, template<class T1, class T2> so I can use the template for all sorts of maps, ie with ints?

  • *"I am trying to implement it"* -- do you mean *call* it? Because that does not look like any kind of function invocation I have ever seen. If you are trying to call it you *should* just be able to do `printMap(myMapOfObjects)` and the compiler will deduce the `T2` template argument. If you want to specify the argument yourself, the syntax would be `printMap(myMapOfObjects)`. – cdhowie Nov 12 '14 at 16:42
  • Just say `printMap(the_map_instance);` – juanchopanza Nov 12 '14 at 16:44
  • @user3956566 Isn't it already a map? – cdhowie Nov 12 '14 at 16:45

1 Answers1

1

Your syntax is wrong for calling the function. You can do so simply like this:

printMap(myMapOfObjects);

And the compiler will deduce the template arguments. Or, if you'd rather be explicit about it:

printMap<myObject>(myMapOfObjects);

The std::map<string, myObject*>& text does not belong in the invocation.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • @user3956566 In your template function try changing `std::map::iterator iter;` to `typename std::map::iterator iter;`. (Just add `typename` before it.) – cdhowie Nov 12 '14 at 16:53
  • 1
    @user3956566 http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords – T.C. Nov 12 '14 at 17:01
  • 1
    @user3956566 Especially with templates, which trip up even the experts on a regular basis. – cdhowie Nov 12 '14 at 17:08
  • 1
    @user3956566 Yup, exactly. If you didn't get what I was saying in my answer I was going to add pretty much exactly that counter-example. :) – cdhowie Nov 12 '14 at 17:14