[C++] Template-Funktion innerhalb einer Klasse

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • [C++] Template-Funktion innerhalb einer Klasse

    Hallo,
    ich versuch gerade eine Klasse mithilfe von Templates zu erweitern, bekomme allerdings einige Probleme.
    Die Dateien schauen wie folgt aus:

    main.cpp
    #include "test.h"

    int main(){
    Test test;
    test.quadrat(6);
    }


    test.h
    class Test{
    public:
    template<class T> bool quadrat(T var);
    };


    test.cpp
    #include <iostream>
    #include "test.h"
    using namespace std;

    template<class T> bool Test::quadrat(T var){
    cout << var * var << endl;
    }



    Wenn ich das mit dem g++ kompilieren will kommt folgende Meldung:
    g++ -c test.cpp
    g++ -o main main.cpp test.o
    /tmp/ccMfJ90O.o: In function `main':main.cpp:(.text+0x2b): undefined reference to `bool Test::quadrat<int>(int)'
    collect2: ld gab 1 als Ende-Status zurück



    Wenn ich das ganze allerdings in eine Datei schreibe funktioniert es:
    #include <iostream>
    using namespace std;

    class Test{
    private:
    public:
    template<class T> bool quadrat(T var);
    };

    template<class T> bool Test::quadrat(T var){
    cout << var * var << endl;
    }

    int main(){
    Test test;
    test.quadrat(6);
    }



    Kann mir jemand bitte sagen, was ich falsch mache?



    MFG genw
  • The export keyword is not implemented

    from http://gcc.gnu.org/bugs.html#known:

    Most C++ compilers (G++ included) do not yet implement export, which is necessary for separate compilation of template declarations and definitions. Without export, a template definition must be in scope to be used. The obvious workaround is simply to place all definitions in the header itself. Alternatively, the compilation unit containing template definitions may be included from the header.