So far, I had a setup where a certain function template getF
was declared like this in the headers
template <typename T> F* getF();
leaving the function body undefined. Then on a shared library, getF
has some specializations..
template<>
F* getF<int>()
{
static int r = 42;
static Finstance(r);
return &Finstance;
}
template<>
F* getF<float>()
{
static float r = 3.14159;
static Finstance(r);
return &Finstance;
}
The above has work so far nicely, as when on a client executable I invoke getF<float>()
, the linker will replace with the appropriate references, and if the specialization doesn't exist in the library, then the compilation will fail with a linker error (which was the desired behavior)
However, Now there should be a small change in the behavior: when the result is not specialized for a given template parameter, the code should build, but return 0 at run-time.
So what I did is change the declaration of getF
like this:
template <typename T> F* getF() { return 0; }
The problem is that, now the compiler will use this definition for all cases, regardless if there is an specialization in the library
Question: Is there some other way to provide some default behaviour for the function at runtime, without moving the specializations to header files?