abc*_*987 5 c++ c-preprocessor
我正在写一个小的Float类,以便更容易地比较浮点数(我们知道,因为浮点数的精度).所以我需要重新加载几乎所有双重运算符.我发现有太多重复,例如operator +,operator-,operator*和operator /.它们很相似.所以我使用宏来减少代码长度.但是当我对它进行编译时,它不起作用.错误是:
happy.cc:24:1: error: pasting "operator" and "+" does not give a valid preprocessing token
happy.cc:25:1: error: pasting "operator" and "-" does not give a valid preprocessing token
happy.cc:26:1: error: pasting "operator" and "*" does not give a valid preprocessing token
happy.cc:27:1: error: pasting "operator" and "/" does not give a valid preprocessing token
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
struct Float
{
typedef double size_type;
static const size_type EPS = 1e-8;
private:
size_type x;
public:
Float(const size_type value = .0): x(value) { }
Float& operator+=(const Float& rhs) { x += rhs.x; return *this; }
Float& operator-=(const Float& rhs) { x -= rhs.x; return *this; }
Float& operator*=(const Float& rhs) { x *= rhs.x; return *this; }
Float& operator/=(const Float& rhs) { x /= rhs.x; return *this; }
};
#define ADD_ARITHMETIC_OPERATOR(x) \
inline const Float operator##x(const Float& lhs, const Float& rhs)\
{\
Float result(lhs);\
return result x##= rhs;\
}
ADD_ARITHMETIC_OPERATOR(+)
ADD_ARITHMETIC_OPERATOR(-)
ADD_ARITHMETIC_OPERATOR(*)
ADD_ARITHMETIC_OPERATOR(/)
Run Code Online (Sandbox Code Playgroud)
我的g ++版本是4.4.3
这是g ++ -E的结果:
struct Float
{
typedef double size_type;
static const size_type EPS(1e-8);
private:
size_type x;
public:
Float(const size_type value = .0): x(value) { }
Float& operator+=(const Float& rhs) { x += rhs.x; return *this; }
Float& operator-=(const Float& rhs) { x -= rhs.x; return *this; }
Float& operator*=(const Float& rhs) { x *= rhs.x; return *this; }
Float& operator/=(const Float& rhs) { x /= rhs.x; return *this; }
};
inline const Float operator+(const Float& lhs, const Float& rhs){ Float result(lhs); return result += rhs;}
inline const Float operator-(const Float& lhs, const Float& rhs){ Float result(lhs); return result -= rhs;}
inline const Float operator*(const Float& lhs, const Float& rhs){ Float result(lhs); return result *= rhs;}
inline const Float operator/(const Float& lhs, const Float& rhs){ Float result(lhs); return result /= rhs;}
Run Code Online (Sandbox Code Playgroud)
gee*_*aur 15
##连接令牌以生成单个令牌; 结果必须是有效的单个令牌.您不需要这样做operator,因为例如operator+实际上不是单个令牌.
#define ADD_ARITHMETIC_OPERATOR(x) \
inline const Float operator x(const Float& lhs, const Float& rhs)\
{\
Float result(lhs);\
return result x##= rhs;\
}
Run Code Online (Sandbox Code Playgroud)
严格地说,您正在为后者生成单个令牌.
实际上是文本预处理器而不是在标记化期间操作的预处理器(例如GCC中的预处理器)通常对此很宽松.