2

Unfornately I couldn't find a post regarding my following problem. I want to write a litte class which overloads the <<-Operator to get variable types of data using templates. The .h-file of my class looks like this:

class MyClass {

    private:
       ...

    public:
        template <typename> void operator<<(T data);
};

The CPP-file:

template <typename T> void MyClass::operator<<(T data) {
    ...
    return;
}

Now I want to use my class:

MyClass mc;
mc << "Test";
mc << 123; 

But my gcc compiler won't compile it giving me following error message:

undefined reference to `void MyClass::operator<< <char const*>(char const*)'

or if i use int for example:

undefined reference to `void MyClass::operator<< <int>(int)'

What am I doing wrong??? Can Someone help me?

Tho Hooves
  • 65
  • 1
  • 3

1 Answers1

1

You have to move the implementation from the .cpp to the .h file. You can define it in place directly:

class MyClass {

    private:
       ...

    public:
        template <class T> 
        void operator << (const T& data)
        {
            //do stuff based on T

            cout << data << " with size:" << sizeof(T);
        }
};
Raxvan
  • 6,257
  • 2
  • 25
  • 46
  • 1
    Not entirely accurate. You don't **have** to move it out of the .cpp file, you just have to ensure that the compiler can instantiate the types you want to use. If you know in advance which types you will be using, then another way of doing it is [explicit instantiation](http://stackoverflow.com/a/2351622/1227469). Also, a common practice is to place the definitions in a separate implementation header, and include that file at the end of the `.h` file. – JBentley Nov 13 '13 at 15:21
  • @JBentley You are right, but i wanted to keep the details out to prevent misunderstanding on the example provided by the question. – Raxvan Nov 13 '13 at 15:31
  • Thank you all for your answers! I moved the function implemention into the header file and it worked! – Tho Hooves Nov 13 '13 at 15:34