【发布时间】:2011-09-16 15:31:18
【问题描述】:
不确定我想做的事情是否不好,但这是我的问题: 我有一些模板功能,例如
std::vector<T> operator - (const std::vector<T>& data1, const std::vector<T>& data2);
std::vector<T> operator * (const std::vector<T>& data1, const std::vector<T>& data2);
std::vector<T> operator & (const std::vector<T>& data1, const std::vector<T>& data2);
....等等。除了运算符之外,所有这些函数都有完全相同的定义,所以我试图写一个这样的宏
#define _BINARY_OP_ON_DATASET (OP_TYPE)
template <typename T> \
std::vector<T> operator OP_TYPE (const std::vector<T>& data1, const std::vector<T>& data2)\
{\
std::vector<T> result;\
result.push_back(data1.begin().val OP_TYPE data1.begin().val)/*sample implementation*/\
return result;\
}
_BINARY_OP_ON_DATASET (&)
_BINARY_OP_ON_DATASET (+)
我得到一堆错误
Error 1 error C2833: 'operator OP_TYPE' is not a recognized operator or type
Error 2 error C2988: unrecognizable template declaration/definition
Error 3 error C2059: syntax error : 'newline'
Error 5 error C2143: syntax error : missing ';' before '<'
Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
...还有更多 谁能看出这是什么问题?
感谢您的帮助。
简历
【问题讨论】:
-
你怎么去
+两个包含T的向量?还有你怎么去&和-这两个向量呢? -
我的错......这是一个错字,编辑过的代码
-
ok.. 正如 Kerrek SB 和 ildjarn 指出的那样,它们是愚蠢的语法错误。
-
好问题,我不知道您可以将非变量类的东西(如运算符)发送到宏。很漂亮,我喜欢宏...*眼泪*
-
每次有人使用宏,上帝都会杀死一只小猫。每次有人滥用操作员超载,上帝就会杀死一只小猫。每次有人用宏滥用运算符重载时,小猫就会直视死亡的眼睛并面临灭绝。 (顺便说一句:您是否考虑过使用
valarray<T>而不是vector<T>?)