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>
.