1

I have been looking some question posted in here, but I still can't find the problem w/ this code:

template <typename ItemType>
class List
{
  public:
    List(); 
  private:
    template <typename ItemType>
    struct Node
    {
      ItemType m_value;
      int      m_count;
      Node*    m_next;
      Node*    m_prev;
    };
    Node* m_head;
    int   m_uniqueSize;
    int   m_size;
    Node* find(const ItemType& value) const;
};

then in the cpp file, I declare the find function like this:

template <typename ItemType>
typename Multiset<ItemType>::Node* Multiset<ItemType>::find(const ItemType& value) const
{
   //linear search code in here
}

is there anything wrong with my code? thx

smith Neil
  • 155
  • 1
  • 7
  • 1
    You cannot put a class template's member function definition in `.cpp` files – Andy Prowl Mar 02 '13 at 22:30
  • so, I have to put everything in header file? – smith Neil Mar 02 '13 at 22:30
  • 1
    Basically, the definition of a template's member functions must be visible to the compiler at the point they are instantiated. Usually, this is achieved by putting those definitions in the same header that contains the class template's definition. – Andy Prowl Mar 02 '13 at 22:32
  • ah. it's working. thx guys :) I've spend hours to figure this problem out – smith Neil Mar 02 '13 at 22:33

2 Answers2

2

The problem is that you are inserting template implementation code inside a .cpp file: all template code must be in header files (you may want to put interface code in a MyClass.h file and implementation code in a MyClass-inl.h file, but both must be header files).

Moreover, you wrote Multiset in your ".cpp" code, but I think you should use List instead of Multiset, according to your first "header" code (the name of the class is List).

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
0

And just to elaborate a bit further on why this is the case with templates, consider that they are evaluated at compile time. Thus their type must be known before the linker kicks in, similar to inline functions, typedefs, etc.

Chris
  • 556
  • 1
  • 4
  • 18