我在.inl文件(visual 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 - &gt;&gt;
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文件中调用header.h中的一个函数
为什么我不能在.inl文件中使用math.h函数?
答案 0 :(得分: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?。