Alex Rivera | Logout

C++ template function compiles in header but not implementation

Asked 2010-06-14T20:03:08.783
31

I'm trying to learn templates and I've run into this confounding error. I'm declaring some functions in a header file and I want to make a separate implementation file where the functions will be defined.

Here's the code that calls the header (dum.cpp):

#include <iostream>
#include <vector>
#include <string>
#include "dumper2.h"

int main() {
    std::vector<int> v;
    for (int i=0; i<10; i++) {
        v.push_back(i);
    }
    test();
    std::string s = ", ";
    dumpVector(v,s);
}

Now, here's a working header file (dumper2.h):

#include <iostream>
#include <string>
#include <vector>

void test();

template <class T> void dumpVector(const std::vector<T>& v,std::string sep);

template <class T> void dumpVector(const std::vector<T>& v, std::string sep) {
    typename std::vector<T>::iterator vi;

    vi = v.cbegin();
    std::cout << *vi;
    vi++;
    for (;vi<v.cend();vi++) {
        std::cout << sep << *vi ;
    }
    std::cout << "\n";
    return;
}

With implementation (dumper2.cpp):

#include <iostream>
#include "dumper2.h"

void test() {
    std::cout << "!olleh dlrow\n";
}

The weird thing is that if I move the code that defines dumpVector from the .h to the .cpp file, I get the following error:

g++ -c dumper2.cpp -Wall -Wno-deprecated
g++ dum.cpp -o dum dumper2.o -Wall -Wno-deprecated
/tmp/ccKD2e3G.o: In function `main':
dum.cpp:(.text+0xce): undefined reference to `void dumpVector<int>(std::vector<int, std::allocator<int> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
make: *** [dum] Error 1

                    
                    
                    
Edit
Report

1 Answer

0

Most compilers don't allow you to put template function definitions in a separate source file, even though this is technically allowed by the standard.

See also:

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.14

answered 2010-06-14T20:20:26.393

Your Answer