Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function specialization symbol matching across libraries

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, getFhas 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?

like image 915
lurscher Avatar asked Aug 07 '26 23:08

lurscher


1 Answers

The best solution is to declare that the library's explicit specializations exist.

// All in the same header file:
template <typename T> F* getF() { return 0; }
template <> F* getF<int>();
template <> F* getF<float>();

This satisfies the rule from Standard 14.7.3/6:

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

like image 191
aschepler Avatar answered Aug 09 '26 16:08

aschepler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!