Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function template specialization is ignored

Tags:

c++

templates

I have written a template function, which uses 2 other template functions (add & mul), in math_functions.h file :

template <typename Dtype>
Dtype mulvadd(Dtype* pa, Dtype* pb, int size, Dtype c)
{
    Dtype result = Dtype(0);
    for (int k = 0; k < size; k++)
    {
        result = add<Dtype>(result, mul<Dtype>(pa[k],pb[k]));
    }
    result = add<Dtype>(result, c);
    return result;
}

int16_t mulv_int16(int16_t* pa, int16_t* pb, int size);

In math_functions.cpp i have different specializations for add & mul, but also specialization for mulvadd for int16_t type :

#include <stdint.h>
#include <fix16.h>
template<> float add<float>(float a, float b) { return a + b;}
template<> float mul<float>(float a, float b) { return a*b;}
template<> int16_t add<int16_t>(int16_t a, int16_t b) { return fix16_sadd(a, b); }
template<> int16_t mul<int16_t>(int16_t a, int16_t b) { return fix16_smul(a, b); }

#ifndef FIXMATH_NO_32BIT
template<> int16_t mulvadd<int16_t>(int16_t* pa, int16_t* pb, int size, int16_t c)
{
    return c + mulv_int16(pa, pb, size);
}
#endif

int16_t mulv_int16(int16_t* pa, int16_t* pb, int size)
{
   ....
}

I have also written a simple test program :

#include "math_functions.h"
int main(int argc, char ** argv) {
    int16_t av[4] = {241,134};
    int16_t bv[4] = {-28, 7};
    int16_t res = mulvadd<int16_t>(av, bv, 2, 0);
    printf("res=%f\n", (double)res);
}

This code compiles without any errors, but the strange thing is that when i call mulvadd the invoked function is the default template defined in the h file and not the specialized version from the cpp file. Any reason why is that happening ?

like image 685
yossiB Avatar asked Oct 03 '26 08:10

yossiB


1 Answers

The compiler will not know about the specializations when it compiles the file with the main function. All it knows are what is in the header file.

Declare the specializations in the header file, so the compiler knows about them.

like image 95
Some programmer dude Avatar answered Oct 05 '26 21:10

Some programmer dude



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!