Funky Visual Studio 2005 bug

I ran into this today with VS2005 SP1: if you define the body of a specialization of a template class’ member function in a separate cpp file, the linker will barf:


template<class T> struct A { void f() {} };
template<> void A<int>::f(); // body in a separate cpp

void main()
{
  A<int> a;
  a.f(); // Linker complains that this function is undefined.
}


You have to define the body in all source files (or at least one) that actually use the specialization of that function, normally in the header file:


template<class T> struct A { void f() {} };
template<> void A<int>::f() { }

void main()
{
  A<int> a;
  a.f();
}


Not sure if I have explained correctly, but I hope you get the idea.

This entry was posted in Uncategorized by Jare. Bookmark the permalink.

1 thought on “Funky Visual Studio 2005 bug

  1. It’s enough to explicitly instantiate the class in the cpp file where you’re specializing the member(s):


    template<> void A<int>::f() { … }

    template struct A<int>; // Explicit instantiation

    JCAB 😉

Comments are closed.