0

I have a member function template of a class declared in source and header as

// c.h
class C {
    public:
    C(){}
    template<typename T> 
    C& operator>>(T& obj);
};

and

// c.cpp
#include <iostream>
#include "c.h"

template<typename T>
C& C::operator>>(T& obj) {
    std::cin >> obj;
    return *this;
}

The main is in a separate file as:

#include <iostream>
#include "c.h"

int main() {
    C c;
    int n;
    c >> n;
    std::cout << n << std::endl;
}

Compiling these results in a link-time error

/usr/bin/ld: /tmp/ccY8edlI.o: in function `main':
main.cpp:(.text+0x23): undefined reference to `C& C::operator>><int>(int&)'
collect2: error: ld returned 1 exit status`

But moving the definition of >> from c.cpp to the file that has main compiles successfully. What's the rule here that causes it to fail in the first case? I looked around and the only related thing I found is a statement on MS docs Local classes are not allowed to have member templates. I'm not sure what local classes are, but it sounds like the opposite of what I have.

Mohammed
  • 313
  • 2
  • 9
  • And your operator implementation is rather peculiar. I suggest you take a look at [basic rules and idioms of operator overloading](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Yksisarvinen Oct 02 '20 at 13:18
  • This is not the actual code. This is just the minimal program that reproduced my error. Or are you referring to the prototype itself. – Mohammed Oct 02 '20 at 13:29
  • Well, the answer to your question is in the duplicate - you must define template functions in header file. My comment is about the declaration `C& operator>>(T& obj);`, which is not an usual way to overload this operator (and `c >> obj` does the same thing as `std::cin >> obj`). – Yksisarvinen Oct 02 '20 at 13:35

0 Answers0