Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a template class that contains a std::map that stores pointers to T which refuses to compile:

template <class T>
class Foo
{
public:
  // The following line won't compile
  std::map<int, T*>::const_iterator begin() const { return items.begin(); }

private:
  std::map<int, T*> items;
};

gcc gives me the following error:

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

Similarly, the following also refuses to compile:

typedef std::map<int, T*>::const_iterator ItemIterator;

However, using a map that doesn't contain the template type works OK, e.g.:

template <class T>
class Foo
{
public:
  // This is OK
  std::map<int, std::string>::const_iterator begin() const { return items.begin(); }

private:
  std::map<int, std::string> items;
};

I assume this is related to templates and begs the question - how can I return a const_iterator to my map?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
381 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use typename:

typename std::map<int, T*>::const_iterator begin() const ...

When this is first passed by the compiler, it doesn't know what T is. Thus, it also doesn't know wether const_iterator is actually a type or not.

Such dependent names (dependent on a template parameter) are assumed to

  • not be types unless prefixed by typename
  • not to be templates unless directly prefixed by template.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...