2016-10-10 61 views
1

我已經寫了模板函數,它使用2個其他模板函數(添加& MUL),在math_functions.h這個頭文件:功能模板特被忽略

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

math_functions.cpp我有不同專業對加& MUL,同時也爲專業化的mulvadd類型int16_t:

#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) 
{ 
    .... 
} 

我也WRI tten一個簡單的測試程序:

#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文件。 任何原因爲什麼會發生?

回答

5

當使用main函數編譯文件時,編譯器不會知道專門化。它所知道的只是頭文件中的內容。

聲明頭文件中的特化,所以編譯器知道它們。

+0

順便說一句,專業化可能是重載而不是(在'mulvadd'中刪除'')。 – Jarod42

+0

謝謝! 所以我很驚訝我沒有得到mulvadd的「多重定義」錯誤 yossiB