2012-07-30 173 views
0

我有一個頭文件在一個.INL文件中的函數模板實現(的Visual C++)麻煩.INL文件C++

麻煩我有這個。

文件math.h - >>

#ifndef _MATH_H 
#define _MATH_H 
#include <math.h> 

template<class REAL=float> 
struct Math 
{ 
    // inside this structure , there are a lot of functions , for example this.. 
    static REAL sin (REAL __x); 
    static REAL abs (REAL __x); 
}; 

#include "implementation.inl"  // include inl file 
#endif 

,這是.INL文件。

implementation.inl - >>

template<class REAL> 
REAL Math<REAL>::sin (REAL __x) 
{ 
    return (REAL) sin ((double) __x); 
} 

template<class REAL> 
REAL Math<REAL>::abs(REAL __x) 
{ 
    if(__x < (REAL) 0) 
     return - __x; 
    return __x; 
} 

正弦函數拋出我的錯誤在運行時,當我把它。但是,abs函數正確工作 。

我覺得麻煩的是調用.INL文件

爲什麼我不能用.INL文件內部文件math.h函數中的頭文件math.h.的功能之一?

+1

您是否要求我們推測您所看到的錯誤? – 2012-07-30 14:39:33

回答

2

該問題與.inl文件無關 - 您只需遞歸調用Math<REAL>::sin(),直到堆棧溢出。在MSVC 10我甚至得到一個很好的警告,指出了這一點:

warning C4717: 'Math<double>::sin' : recursive on all control paths, function will cause runtime stack overflow 

嘗試:

return (REAL) ::sin ((double) __x); // note the `::` operator 

此外,作爲一個側面說明:宏的名稱_MATH_H保留給編譯器實現使用。在許多使用實現保留的標識符的情況下,實際上遇到衝突會有些不幸(儘管您應該避免使用這種名稱)。但是,在這種情況下,該名稱與math.h實際上可能用於防止自己被多次包含的名稱相沖突的可能性相當高。

你應該選擇一個不太可能衝突的不同名稱。有關規則,請參閱What are the rules about using an underscore in a C++ identifier?