如何在任何容器上进行宏工作?

时间:2017-12-21 14:40:51

标签: c++ macros

我有以下代码,我正在使用宏来检查向量中是否存在元素。

#define x.contains(a) x.find(a)!=x.end()
void main(){
     vector<int> v = {1,2,3,4};
     if(v.contains(2))
         cout<<"yes"<<endl;
     else
         cout<<"no"<<endl;
}

但是在编译时会出现以下错误:

ISO C++11 requires whitespace after the macro name #define x.contains(a) x.find(a)!=x.end()

请给我一个出路。 感谢。

1 个答案:

答案 0 :(得分:1)

宏不再是解决方案了。

如果你想要朝这个方向努力,你需要让你的宏看起来像一个函数而不是一个成员函数,并且还使用唯一的括号来避免与运算符优先级相关的意外影响:

#define contains(x,a) ((x).find(a)!=(x).end())

但是如果你这样做,很遗憾不使用C ++模板而不是宏。例如:

template <class T, class U> 
bool contains (const T& x, U a) {
    return x.find(a)!=x.end();
}

模板优于宏的一个巨大优势是可以定义特化。然后编译器选择最合适的实现。 例如,宏版本和我之前的示例都不能与<list>一起使用,因为没有find()成员函数。但是使用模板,您可以定义更专业的版本:

template <class U>
bool contains (const list<U>& x, U a) {
    return std::find(x.begin(), x.end(), a)!=x.end();
}

<强> Online demo