I\'d like to provide a library that provides template code. But I would also like to keep the most possible the ownership of this code (generated code) when I can guess the
You have to hide the implementation in the header file.
//lib1.h
template
void print_me();
//lib1.cpp
#include
#include "lib1.h"
template
void print_me()
{
std::cout << printme << std::endl;
}
template void print_me<0>();
template void print_me<1>();
What is happening is how templates are typically used: they are only built when needed (else you'd have to build a print_me for all integers), so they figure out the implementation when the software runs (which is why it slows down compilation time so much, it rebuilds the class for every compilation unit that uses the template). As long as you have the definition of the template, you can build it for whatever argument you need. This is one of the few cases where hiding the definition in the .cpp file is semi valid, but the end user will typically get one hell of a useless error for print_me<2>(). It'd be better (imho) to use this framework (C++11):
//lib1.h
#include
template
typename std::enable_if::type print_me();
//lib1.cpp
#include
#include "lib1.h"
template
typename std::enable_if::type print_me()
{
std::cout << N << std::endl;
}
template void print_me<0>();
template void print_me<1>();
now the error is "no matching function for call to print_me()" which is a little better...you could do a nested function with a static_assert to make it even better.