Macros are not the solution anymore.
If you want nevertheless to pursue in this direction, you need to make your macro look like a function instead of a member function, and also use sole parentheses to avoid unexpected effects related to operator precedence:
#define contains(x,a) ((x).find(a)!=(x).end())
But if you go this way, it would be a pity not to use C++ templates instead of the macros. For example:
template <class T, class U>
bool contains (const T& x, U a) {
return x.find(a)!=x.end();
}
One huge advantage of templates over macros, is the possibility to define specializations. The compiler then choses the most suitable implementation.
For instance, neither the macro version nor my previous example can work with <list>
, because there's no find()
member function. But with templates, you can define a more specialized version :
template <class U>
bool contains (const list<U>& x, U a) {
return std::find(x.begin(), x.end(), a)!=x.end();
}
Online demo