[Solved] Template function in seperate cpp file



  • I use Qt 5.0.1 and created simple Qt Gui Application. Then I created QtHarrixLibrary.cpp:
    @#include "QtHarrixLibrary.h"

    template <class T> T funcT(T x)
    {
    return 2*x;
    }

    int func(int x)
    {
    return 2*x;
    }
    @

    and QtHarrixLibrary.h files:
    @#ifndef QTHARRIXLIBRARY_H
    #define QTHARRIXLIBRARY_H

    template <class T> T funcT(T x);

    int func(int x);

    #endif // QTHARRIXLIBRARY_H
    @

    Then I added files in project (Add Existing Files...), added in mainwindow.cpp code:
    @#include "QtHarrixLibrary.h"@

    Then added pushButton and textEdit. And pushButton has slot:
    @void MainWindow::on_pushButton_clicked()
    {
    int x=5;

    int y=func(x);
    
    ui->textEdit->insertPlainText(QString::number(y)+"\n");
    
    y=funcT(y);
    
    
    ui->textEdit->insertPlainText(QString::number(y)+"\n");
    

    }
    @

    And I have errors:
    C:\Qt\untitled4\mainwindow.cpp:26: error: undefined reference to `int funcT<int>(int)'
    collect2.exe:-1: error: error: ld returned 1 exit status

    When I use only function func program is working. When I don't use seperate cpp file and add funcT in mainwindow.cpp program ia working.

    How fix it?



  • Hi,

    template functions and classes shall be known to the compiler at Compile Time not at Link Time.

    When you use templates you can

    Include template implementations in header file

    Define a external source included in header file

    Example 1
    QtHarrixLibrary.h
    @
    #ifndef QTHARRIXLIBRARY_H
    #define QTHARRIXLIBRARY_H

    template <class T> T funcT(T x)
    {
    return 2*x;
    }

    int func(int x);

    #endif // QTHARRIXLIBRARY_H
    @

    QtHarrixLibrary.cpp

    @
    #include "QtHarrixLibrary.h"

    int func (int x)
    {
    return 2*x;
    }
    @

    Example 2
    QtHarrixLibrary.h
    @
    #ifndef QTHARRIXLIBRARY_H
    #define QTHARRIXLIBRARY_H

    template <class T> T funcT(T x);

    int func(int x);

    #include "QtHarrixLibrary.tpp"
    #endif // QTHARRIXLIBRARY_H
    @

    QtHarrixLibrary.cpp
    @
    #include "QtHarrixLibrary.h"

    int func (int x)
    {
    return 2*x;
    }
    @

    QtHarrixLibrary.tpp
    @
    template <class T>
    T funcT (T x)
    {
    return 2*x;
    }
    @

    Last TIP:
    use
    @template <typename T>@

    instead of

    @template <class T>@



  • Thank you so much! Everything works!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.