我编写了一个模板函数,它在math_functions.h文件中使用了另外两个模板函数(add&mul):
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);
Run Code Online (Sandbox Code Playgroud)
在math_functions.cpp中,我对add&mul有不同的特化,但对于int16_t类型的mulvadd也有特殊化:
#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)
{
....
}
Run Code Online (Sandbox Code Playgroud)
我还写了一个简单的测试程序:
#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);
}
Run Code Online (Sandbox Code Playgroud)
这段代码编译没有任何错误,但奇怪的是,当我调用mulvadd时,调用的函数是h文件中定义的默认模板,而不是cpp文件中的专用版本.有什么理由发生这种情况?