1

I'm pretty new with templates, so please don't be harsh on me if my code is very wrong :) This is the header file for a class Key that uses a template:

//Key.h
#ifndef KEY_H
#define KEY_H

#include "../Constants.h"

template<class KeyType>

class Key
{
    public:
        Key<KeyType>(KeyType initial);          
        KeyType increment();

    private:
        KeyType current;

};

#endif /* KEY_H */ 

This is the .cpp file of Key class:

//Key.cpp
#include "Key.h"

template<class KeyType> Key<KeyType>::Key(KeyType p_initial)
{
    this->current = p_initial;
}

template<class KeyType> KeyType Key<KeyType>::increment()
{
    this->current ++; //KeyType should implement this operator
}

So what's the problem? I try to create an instance of Key somewhere else in my code, like this:

Key songID (0); // ERROR: undefined reference to Key<int>::Key(int)

and then use

songID.increment(); // ERROR: undefined reference to Key<int>::increment()

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
  • First of all, you have to put generic template definitions in the same file as the declarations ([see here](http://stackoverflow.com/questions/648900/c-templates-undefined-reference?rq=1)). Secondly, you probably don't want the `` part in `Key(KeyType initial);`, or any of the others. – chris Apr 14 '13 at 06:09

1 Answers1

1

Two points:

masoud
  • 55,379
  • 16
  • 141
  • 208