2012-07-30 176 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?