Template Operator Linker Error

I have a linker error that I led to a simple example. Build Output:

debug / main.o: In the log & function, enter :: operator & & Lt; Lt; (charconst (&) [6]) 'collect2: ld returned 1 exit statusmain':
C:\Users\Dani\Documents\Projects\Test1/main.cpp:5: undefined reference to

The linker seems to be ignoring the definition in log.cpp.
I also canโ€™t put the definition in log.h because I add the file many times and it complains about overriding.

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;
}
+3
source share
3 answers

I assume this is your first use of templates, so I will try to be didactic.

. , , . , , : , .

:

template <class T>
void foo(T t) { std::cout << t << "\n"; }

, - .

int i;
foo(i); // [1]

template. , , T int.

double d;
foo(d);    // Another instantiation, this time with `T` replaced by `double`
foo(d);    // foo<double>() already exists, it reused

. , , .

, 2 :

2 .

(1) . , . , ( , , )

(2) . :

  • (template <> void foo<int>();), ,
  • ,

, , , .

gcc , .

, , . , , , ODR: . , , , ( ). , , , .

+4

, export cpp. , ( ) export , , , - .

+1

You have two standard options:

+1
source

Source: https://habr.com/ru/post/1749229/


All Articles