lundi 28 novembre 2016

C++ template explicit instantiation declarations: best practices

My question is how we should use template explicit instantiation declarations in a right way?

Suppose we have some template class template<class T> Foo.

Here is my mind how to deal with this feature:

We put template declaration in Foo.h file, implementation in Foo.inl file, include this Foo.inl in the end of the Foo.h file, put extern template class Foo<int>; after #include "Foo.inl". Also we should use explicit template instantiation definition in, for example, Foo.cpp file (of course we should also inlcude Foo.h in this cpp file).

If we do all this stuff we got an error: we cannot use explicit template instantiation definition just after explicit template instantiation declaration. Ok, lets put template declaration and #include "Foo.inl" in separate file Foo.hpp and include it in Foo.cpp. Eventually we got this:

Foo.hpp

template<class T>
class Foo
{
public:
  Foo();
  ...
};

#include "Foo.inl"

Foo.inl

template<class T>
Foo<T>::Foo() {}

Foo.h

#include "Foo.hpp"
extern template class Foo<int>;

Foo.cpp

#include "Foo.hpp"
template class Foo<int>;

And use this template ike this:

test1.cpp

#include "Foo.h"
void bar()
{
  Foo f;
}

Too many Foo's do not you think? How do you deal with this?

Sorry for my english.

Aucun commentaire:

Enregistrer un commentaire