gpt4 book ai didi

c++ - 函数模板特化被忽略

转载 作者:行者123 更新时间:2023-11-30 00:46:03 25 4
gpt4 key购买 nike

我在ma​​th_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);

ma​​th_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)
{
....
}

我也写了一个简单的测试程序:

#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);
}

这段代码编译没有任何错误,但奇怪的是,当我调用 mulvadd 时,调用的函数是 h 文件中定义的默认模板,而不是 cpp 文件中的专用版本。发生这种情况的原因是什么?

最佳答案

编译器在使用 main 函数编译文件时不会知道特化。它只知道头文件中的内容。

在头文件中声明特化,以便编译器了解它们。

关于c++ - 函数模板特化被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com