Я пишу небольшой класс Floatдля облегчения сравнения чисел с плавающей запятой (как мы знаем, из-за точности числа с плавающей запятой). Поэтому мне нужно перезагрузить почти все операторы, которые есть у double. Я нахожу, что слишком много повторов, таких как 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
Вот мой код:
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(/)
И моя версия 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;}