Template operator linker error

Posted by Dani on Stack Overflow See other posts from Stack Overflow or by Dani
Published on 2010-06-09T15:26:11Z Indexed on 2010/06/09 15:32 UTC
Read the original article Hit count: 325

Filed under:
|
|

I have a linker error I've reduced to a simple example. The build output is:

debug/main.o: In function main':
C:\Users\Dani\Documents\Projects\Test1/main.cpp:5: undefined reference to
log& log::operator<< (char const (&) [6])'
collect2: ld returned 1 exit status

It looks like the linker ignores the definition in log.cpp.
I also cant put the definition in log.h because I include the file alot of times and it complains about redefinitions.

main.cpp:

#include "log.h"

int main()
{
    log() << "hello";
    return 0;
}

log.h:

#ifndef LOG_H
#define LOG_H

class log
{
public:
    log();
    template<typename T>
    log &operator <<(T &t);
};

#endif // LOG_H

log.cpp:

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

log::log()
{
}

template<typename T>
log &log::operator <<(T &t)
{
    std::cout << t << std::endl;
    return *this;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates