Frage

Function header:(Templated Outer Class Map has inner class Iterator)

Iterator insert(const std::pair<const T1, T2>&);

Function Implementation:

template<typename T1, typename T2>
typename Map<T1,T2>::Iterator insert(const std::pair<const T1, T2> &p)

Code to call insert function:

std::pair<int,char>p = std::make_pair(5, 'z');
mymap3.insert(p);

Compilation with g++ -g -std=c++11, Error:

 In function `main':
testmap.cpp:535: undefined reference to 
Map<int, char>::insert(std::pair<int const, char> const&)'
collect2: error: ld returned 1 exit status

Why does the compiler assumer the definition of insert is now (pair const &) instead of my definition of (const pair &) is there a difference? Am I calling this inappropriately? I'm very befuddled. Yes, this is for class, we are re-implementing map. So the function definition was a given, I just need to find out how to call it and make it work.

War es hilfreich?

Lösung

This function:

template<typename T1, typename T2>
typename Map<T1,T2>::Iterator insert(const std::pair<const T1, T2> &p)

when declared outside the class definition of Map, is not a member function - it defines a global insert.

This is a member of Map<T1, T2> declared at namespace scope (i.e., outside the class definition):

template<typename T1, typename T2>
typename Map<T1,T2>::Iterator Map<T1,T2>::insert(const std::pair<const T1, T2> &p)

Note that the member function name has been qualified by the class name, which in this case is Map<T1, T2>.

On a related note, using a trailing return type would let you get rid of some of the nastiness in the return type, since names in a trailing return type are resolved in the scope of the class:

template<typename T1, typename T2>
auto Map<T1, T2>::insert(const std::pair<const T1, T2> &p) -> Iterator;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top