Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -- Can I use a template function that is not implemented in a header file? [duplicate]

Tags:

c++

templates

Possible Duplicate:
Storing C++ template function definitions in a .CPP file
Why can templates only be implemented in the header file?
Why should the implementation and the declaration of a template class be in the same header file?

I have three files. In one, base.h, I have a class that has a member utilizing a template:

class Base {
    protected:
        template <class T>
            void doStuff(T a, int b);
};

In base.cpp, I implement Base::doStuff():

#include "base.h"

template <class T>
void Base::doStuff(T a, int b) {
    a = b;
}

I then try to use this in another class in my project:

#include "base.h"

void Derived::doOtherStuff() {
    int c;
    doStuff(3, c);
}

But I get a linking error that states that it can't find 'doStuff(int, int)'

From what I've seen, this is not possible in C++03 without moving the implementation of this function into the header file. Is there a clean way to do this? (I'm fine with using C++11x features).

like image 539
crosstalk Avatar asked Oct 07 '22 02:10

crosstalk


1 Answers

Its a common idiom to place template definitions into an .inl file along with inline function definitions, and include it at the end of .h file:

base.h

#ifndef BASE_H
#define BASE_H

class Base {
    protected:
        template <typename T>
        void doStuff(T a, int b);
};

#include "base.inl"

#endif

base.inl

template <typename T>
void Base::doStuff(T a, int b) {
    a = b;
}
like image 157
yuri kilochek Avatar answered Oct 13 '22 10:10

yuri kilochek