Let\'s say I have a bunch of well-known values, like this (but const char *
is just an example, it could be more complicated):
const char *A = \"A\"
This can be done using variadic functions in c++03 as follows:
template
bool MatchesOne( T _lhs, int _count, ...)
{
va_list vl;
va_start(vl,_count);
for (int i=0;i<_count;i++)
{
int rhs=va_arg(vl,int);
cout << "rhs = " << rhs << endl;
if (_lhs == rhs) return true;
}
va_end(vl);
return false;
}
int main(){
float ff = 3.0;
if (MatchesOne(ff, 5, 1, 2, 4, 5, 3))
{
cout << "Matches" << endl;
}
return 0;
}
If you know the types of all the expressions will have the same type as _lhs, you can change int rhs=va_arg(vl,int);
to T rhs=va_arg(vl,T);
You can also do this elegantly using variadic templates in c++11:
template
bool one_equal(const T & _v1, const T2 & _v2)
{
return _v1 == _v2;
}
template
bool one_equal(const T & _v1, const T2 & _v2, Args... args)
{
return _v1 == _v2 || one_equal(_v1, args...);
}
...
if (one_equal(some_complicated_expression, v1, v2, v3, v4))
{
}
Okay one final hack-ish solution. It works, but makes the implementer of this function do a lot of repetitive work.
template
bool match_one(T1 _v1, T2 _v2)
{
return _v1 == _v2;
}
template
bool match_one(T1 _v1, T2 _v2, T3 _v3)
{
return _v1 == _v3 || match_one(_v1, _v2);
}
template
bool match_one(T1 _v1, T2 _v2, T3 _v3, T4 _v4)
{
return _v1 == _v4 || match_one(_v1, _v2, _v3);
}
template
bool match_one(T1 _v1, T2 _v2, T3 _v3, T4 _v4, T5 _v5)
{
return _v1 == _v5 || match_one(_v1, _v2, _v3, _v4);
}