How to remove a template class method from a header to cpp?
3 answers
It must be remembered that a template generates class code only when you use this template in a program with specific parameters. This means that you cannot compile a module containing just a class template. A template is not yet a type (in C #, on the contrary, angle brackets refer to the Generic type). Thus, the method implementation must be in the module where this method is used, otherwise you will get an Unresolved symbol. Here is an example that was compiled in MSVS 2008:
foo.h:
#pragma once template<class T> class Foo { public: T bar(T a) const; }; main.cpp
#include "foo.h" template<class T> T Foo<T>::bar(T a) const { return a; } int main(int argc, char *argv[]) { Foo<int> a; int b = a.bar(3); return 0; } Obviously, in this example, this is equivalent to the variant when the implementation of the method is located in the header file.
In general, if you have such a problem, it is worth considering whether you are on the right path, so to speak :)
If you know with what types this method will be instantiated to a template class, then you can take out these specializations. For example, like this:
foo.h
#pragma once template<class T> class Foo { public: T bar(T a) const; }; foo.cpp
template<> int Foo<int>::bar(int a) const { return a; } main.cpp
#include "foo.h" int main(int argc, char *argv[]) { Foo<int> a; int b = a.bar(3); return 0; } At the same time, instantiating (more precisely, calling the method bar ) with any other type other than int will result in an error.
Here is a very elegant method, I used it myself: http://www.gamedev.ru/code/tip/?id=5303
// main.cpp #include "Templ.h" int main() { Templ<int> templ(0); Templ<float> templF(0.0f); Templ<double> templD(0.0); return 0; } // Templ.h #pragma once template <typename T> class Templ { public: Templ(T t); private: T x; }; // Templ.cpp #include "Templ.h" template Templ<int>; template Templ<float>; template <typename T> Templ<T>::Templ(T t) : x(t) { } - This is just a preliminary instantiation, i.e. instantiation (generation of code by a function template) is not in the place where it is called, but in the place where the specialization is declared. This is off topic. - IAZ
- oneNo, it's all about the case. Only instantiation of a class with a
doubletemplate is not enough (it is used in the example). In my opinion, this is the most correct way to fix specific implementations of templates incpp, +1 - mega