1

For the following code:

#include <map>
#include <iostream>
#include <string>

using namespace std;

template <class T>
class Foo{
  public:
    map<int, T> reg;
    map<int, T>::iterator itr;

    void add(T  str, int num) {
      reg[num] = str;
    }

    void print() {
      for(itr = reg.begin(); itr != reg.end(); itr++) {
        cout << itr->first << " has a relationship with: ";
        cout << itr->second << endl;
      }
    }
};

int main() {
  Foo foo;
  Foo foo2;
  foo.add("bob", 10);
  foo2.add(13,10);
  foo.print();
  return 0;
}

I get the error:

 type std::map<int, T, std::less<int>, std::allocator<std::pair<const int, T> > > is not derived from type Foo<T>

I've never used C++ templates - What does this mean?

Kay
  • 845
  • 7
  • 21
  • 33
  • +1 for including the error message. Next time also indicate what line it's on (putting a comment in the source code is a good way to accomplish this). – Ben Voigt Jan 16 '11 at 01:18

1 Answers1

3

You're missing the type when you declare instances of Foo.

In your case, you would want:

  Foo<std::string> foo;
  Foo<int> foo2;

You will also need to add the keyword typename to the line:

    typename map<int, T>::iterator itr;

See here for why you'll need typename.

Edit, here's a modified version of your code that compiles and runs locally:

#include <map>
#include <iostream>
#include <string>

using namespace std;

template <class T>
class Foo{
public:
    map<int, T> reg;
    typename map<int, T>::iterator itr;

    void add(T  str, int num) {
        reg[num] = str;
    }

    void print() {
        for(itr = reg.begin(); itr != reg.end(); itr++) {
            cout << itr->first << " has a relationship with: ";
            cout << itr->second << endl;
        }
    }
};

int main() {
    Foo<std::string> foo;
    Foo<int> foo2;
    foo.add("bob", 10);
    foo2.add(13,10);
    foo.print();
    return 0;
}
Community
  • 1
  • 1
Mic
  • 6,741
  • 3
  • 24
  • 25