1

Is it possible to define weakly linked template specializations?

In math_functions.h I have:

namespace utils {

template <typename T_TYPE>
T_TYPE sqrt(T_TYPE value);

template <>
float sqrt(float value) __attribute__((weak));

template <>
double sqrt(double value) __attribute__((weak));

template <>
long double sqrt(long double value) __attribute__((weak));

} // End namespace utils.

In math_functions.cpp, I have the default implementations of the template specializations which I want to be over-ridable:

namespace utils {

template <>
float sqrt(float value) {
    return sqrtf(value);
}

template <>
double sqrt(double value) {
    return sqrt(value);
}

template <>
long double sqrt(long double value) {
    return sqrtl(value);
}

} // End namespace utils.

I then have a target specific file for the microcontroller which should provide a more efficient sqrt function, specific to the hardware. I want this definition to override the default utils::sqrt<float> specialization:

hw.cpp:

namespace utils {

template <>
float sqrt<float>(float value) {
    float out;
    // Use hardware assembler call to run SQRT on VFPU.
    __asm("VSQRT.F32 %0,%1" : "=t"(out) : "t"(value));
    return out;
}

} // End namespace utils.

Is what I want to do even possible?

With the code above GCC complains about multiple definititions of utils::sqrt.

  • 5
    Why a template? Just overload them. Then you won't have the additional burden of juggling burning template specializations. – StoryTeller - Unslander Monica Jan 23 '18 at 09:58
  • No need for esoteric non-portable configurations. Put your math functions in a static library (specialisations or overloads, your choice, but overloads are preferable). – n. m. could be an AI Jan 23 '18 at 10:00
  • And in general, if you're trying to use weak symbols and having trouble, you should examine the symbols in the intermediate object files to see what's going on. Details are, of course, platform-specific. – Useless Jan 23 '18 at 10:01
  • @StoryTeller Good call on the overloading, I solved the issue with that. However, I would still like to know if it is possible to weak-link template specializations. – Erik Van Hamme Jan 23 '18 at 11:25

0 Answers0