0

Suppose that I write a class template, say Vector<typename T>. I want to expose using fvec = Vector<float>; and using dvec = Vector<double>; to my clients.

Ideally, I do not want my clients know how the template Vector is implemented, or better, they need only know the existence of fvec and dvec and a pre-compiled file.

Ma Ming
  • 1,765
  • 2
  • 12
  • 15

2 Answers2

0

if you want to deliver the clients just header file and implementation just for double and float, you can explicit instantiate the template class into cpp file.

http://en.cppreference.com/w/cpp/language/class_template

e.g. you need something like this in cpp file

 template class Vector<float>;
 template class Vector<double>;

For easy usage, you can also do some typedefs in h file - this is because someone might decide to use it with "quadruple" type (libquadmath)

Alternatively you can create tho more clases into h file that inherits from the template, but this is same as typedefs.

Nick
  • 9,962
  • 4
  • 42
  • 80
0

Here's a simple program that builds and runs. The implementation of the class template Foo is hidden in Foo.cc.

Foo.h

#pragma once

template <typename T> class Foo
{
   public:

      Foo();

      void test();
};

template class Foo<float>;
template class Foo<int>;

Foo.cc

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

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

template <typename T> void Foo<T>::test()
{
   std::cout << "Came to Foo<T>::test\n";
}

main.cc

#include "Foo.h"

int main()
{
   Foo<int> f1;
   f1.test();

   Foo<float> f2;
   f2.test();

   // Uncommenting these lines results in linker error.
   // Foo<double> f3;
   // f3.test();
}

Command to build:

g++ -Wall -std=c++11 Foo.cc main.cc -o program

I am also able to build using:

g++ -Wall -std=c++11 -c Foo.cc
g++ -Wall -std=c++11 -c main.cc
g++ -Wall -std=c++11 Foo.o main.o -o program

You can ship Foo.h and a library that contains Foo.o. Your clients will be limited to using Foo<int> and Foo<float>.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    template class Foo; template class Foo; Those can be in .cc file as well. – Nick Dec 21 '16 at 15:28
  • 1
    @Nick, that too will work. I still prefer to have them in the .h file since it expresses the intent better -- that `Foo` can be used with `int` and `float` and nothing else. – R Sahu Dec 21 '16 at 15:45