Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Linker Problem mit Template Class

5 views
Skip to first unread message

Henning Follmann

unread,
Feb 8, 2017, 1:00:04 PM2/8/17
to
Ich habe hier ein Problem beim Linken mit einer template class. Ich habe
einmal ein vereinfachtes Beispiel zusammengestellt:

printer.hpp
====================================
#ifndef _PRINTER_HPP_INCLUDE_
#define _PRINTER_HPP_INCLUDE_
#include <iostream>

template <typename T1>
class printer{
std::ostream& _out;

public:
printer(std::ostream& os):_out{os} {};

void operator()(T1 var);

};

#endif
====================================

printer.cpp
====================================
#include "printer.hpp"



template <typename T1>
void printer<T1>::operator()(T1 var){
_out<<var<<"\n";

}
====================================

maintest.cpp
====================================
#include <iostream>
#include "printer.hpp"

int main()
{
printer<int> prntr{std::cout};
prntr(25);
return 0;
};
====================================

Die Uebersetzung schlaegt fehl. Genauer gesagt, die Bindung:
g++ -std=c++11 maintest.cpp printer.cpp
/tmp/ccRR5tP2.o: In function `main':
maintest.cpp:(.text+0x26): undefined reference to
`printer<int>::operator()(int)'
collect2: error: ld returned 1 exit status

Ist das ein Fehler des Linkers?


Gruss
Henning





--
Henning Follmann | hfol...@itcfollmann.com

Stefan Reuther

unread,
Feb 9, 2017, 12:50:03 PM2/9/17
to
Am 08.02.2017 um 16:48 schrieb Henning Follmann:
> Ich habe hier ein Problem beim Linken mit einer template class. Ich habe
> einmal ein vereinfachtes Beispiel zusammengestellt:
[...]
> printer.cpp
> ====================================
> #include "printer.hpp"
>
> template <typename T1>
> void printer<T1>::operator()(T1 var){
> _out<<var<<"\n";
> }

Die Template-Instanziierung muss ins Headerfile, damit der Compiler das
Template sieht, wenn er es instanziieren muss.


Stefan
0 new messages