0

Possible Duplicate:
Why do I get “unresolved external symbol” errors when using templates?
Why can templates only be implemented in the header file?

Maybe I'm just too stupid for it, but this doesn't work for me:

Foo.h

#ifndef FOO_H
#define FOO_H

class Foo {
public:
    template<typename T>
    void foo(T const &);
};

#endif // FOO_H

Foo.cpp

#include "Foo.h"

template<typename T>
void Foo::foo(T const &var) {
    // do something useless
}

main.cpp

#include "Foo.h"

int main() {
    int i;
    Foo bar;
    bar.foo(i);
}

I simply compiled with Xcode 4.4.1 but it returns me the following linking error:

Undefined symbols for architecture x86_64:
  "void Foo::foo<int>(int const&)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks for any reply!

Community
  • 1
  • 1
qwertz
  • 14,614
  • 10
  • 34
  • 46
  • 1
    We *literally* just had [this very same question](http://stackoverflow.com/q/12446875/596781)... its template Sunday all over again :-) – Kerrek SB Sep 16 '12 at 13:01

2 Answers2

3

Template method definitions must be available at the point of instantiation. Try placing the definition of the method in the header file.

Andrew Durward
  • 3,771
  • 1
  • 19
  • 30
0

You will have to provide an inline definition if you don't want to bother with explicit instantiation. The other solution is to provide explicit instantiations in the .cpp file.

See http://www.parashift.com/c++-faq-lite/separate-template-fn-defn-from-decl.html for more information.

Attila Mika
  • 113
  • 1
  • 5