我正在开发一个需要使用多种算术类型的项目。因此,我创建了一个头文件,在其中定义了用户自定义算术类型的最小要求:
user_defined_arithmetic.h:
typedef double ArithmeticF; // The user chooses what type he
// wants to use to represent a real number
namespace arithmetic // and defines the functions related to that type
{
const ArithmeticF sin(const ArithmeticF& x);
const ArithmeticF cos(const ArithmeticF& x);
const ArithmeticF tan(const ArithmeticF& x);
...
}
令我烦恼的是,当我使用以下代码时:
#include "user_defined_arithmetic.h"
void some_function()
{
using namespace arithmetic;
ArithmeticF lala(3);
sin(lala);
}
我遇到了编译器错误:
error: call of overloaded 'sin(ArithmeticF&)' is ambiguous
candidates are:
double sin(double)
const ArithmeticF arithmetic::sin(const ArithmeticF&)
我从未使用过<math.h>
头文件,只使用过<cmath>
。我从未在头文件中使用过using namespace std
。我正在使用gcc 4.6.*。我检查了含有模糊声明的头文件是什么,结果是:mathcalls.h:
Prototype declarations for math functions; helper file for <math.h>.
...
我知道,<cmath>
包括 <math.h>
,但它应该通过std命名空间来保护声明。我深入研究了 <cmath>
头文件并发现:
cmath.h :
...
#include <math.h>
...
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef abs
#undef div
#undef acos
...
namespace std _GLIBCXX_VISIBILITY(default)
{
...
所以命名空间std是在包含之后开始的。这里有什么问题吗,还是我理解错了什么?
using namespace X
。或者,您可以使用using指令(using arithmetic :: sin
)。最后,通过编辑“typedef”更改类型的整个方法真的是一个糟糕的想法。 - David Rodríguez - dribeastypedef
。这意味着用户可以知道他们正在使用的类型,而无需在头文件中搜索typedef
。此外,你将能够在单个应用程序中使用多种类型。 - David Rodríguez - dribeasabs
、三个log
等。这些重载分别是int
、double
和long double
,以适应您的需求。但是C只有每个函数的一个版本。 - jww