Better way to say x == Foo::A || x == Foo::B || x == Foo::C || …?

别等时光非礼了梦想. 提交于 2019-12-03 16:18:51

问题


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", *B = "B", *C = "C", *D = "D", *E = "E", *F = "F", *G = "G";

Now let's say I want to behave in a particular way if the result of some expression is in a subset of those:

if (some_complicated_expression_with_ugly_return_type == A ||
    some_complicated_expression_with_ugly_return_type == C ||
    some_complicated_expression_with_ugly_return_type == E ||
    some_complicated_expression_with_ugly_return_type == G)
{
    ...
}

I find myself typing this sort of thing often enough that I would like a shorthand for it.

If the language was Python, I could easily say:

if some_complicated_expression_with_ugly_return_type in [A, C, E, G]:
    ...

Is there a well-known, portable way for me to express this similarly in C++03?

Note that the return type is itself ugly (almost as ugly as the return type of lambda expressions), so I certainly don't want to store it in a local variable.

But the return type does not have to match that of the constants -- for example, if the return type was std::string, it would not be implicitly convertible to const char *, but operator == would be perfectly fine for the comparison.

So far, the best solution I have is to say something like:

const char *items[] = { A, C, E, G };
if (std::find(items, items + sizeof(items) / sizeof(*items),
              some_complicated_expression_with_ugly_return_type)
    != items + sizeof(items) / sizeof(*items))
{
    ...
}

but it's pretty darn ugly. Is there a better way, which also works for non-PODs?


回答1:


You could factor your current best solution into a template:

template<class A, class B, size_t n>
inline bool is_in(const A &a, B (&bs)[n]) {
  return std::find(bs, bs + n, a) != bs + n;
}

which you can use like

X items[] = { A, C, E, G };
if (is_in(some_complicated_expression_with_ugly_return_type, items))
  …



回答2:


If you have C++11:

auto res = some_complicated_expression_with_ugly_return_type;
if (res == A
    || res == C
    || res == E
    || res == G) {
}

if not, you can still eliminate the type declaration by using a template function:

template <class T>
bool matches(T t) {
    return t == A || t == C || t == E || t == G;
}

if (matches(some_complicated_expression_with_ugly_return_type)) {
}



回答3:


You could use a switch:

switch (some_complicated_expression_with_ugly_return_type) {
  case A: case C: case E: case G:
    // do something
  default:
    // no-op
}

This only works with integer and enum types, note.

For more complex types, you can use C++11's auto, or for C++03, boost's BOOST_AUTO:

auto tmp = some_complicated_expression_with_ugly_return_type;
// or
BOOST_AUTO(tmp, some_complicated_expression_with_ugly_return_type);

if (tmp == A || tmp == C || tmp == E || tmp == G) {
  // ...
}



回答4:


(Edit: Turns out my original trick with a dummy type didn't work, I was misled by a lucky accident in my tests. Let's try that again...)

With a couple of helper templates you can write a general solution for this kind of situation:

template <typename T1> class Matcher {
public:
    explicit Matcher(T1 t1): val(t1), flag(false) {}
    template <typename T2> Matcher& operator()(T2 t2)
        { flag |= val == t2; return *this; }
    operator bool() const { return flag; }
private:
    T1 val;
    bool flag;
};
template <typename T1> Matcher<T1> match(T1 t1) { return Matcher<T1>(t1); }

// example...
string s = whatever;
if (match(s)("foo")("bar")("zap")) { do_something(); }

You can match against as many arguments as you want.




回答5:


Expressions of the type

if (some_complicated_expression_with_ugly_return_type == A ||
    some_complicated_expression_with_ugly_return_type == C ||
    some_complicated_expression_with_ugly_return_type == E ||
    some_complicated_expression_with_ugly_return_type == G)
{
    ...
}

are quite common in code (well, a pre-computed expression is anyway). I think the best you can do for readability is pre-compute the expression and keep it as is.

ugly_return_type x = some_complicated_expression_with_ugly_return_type;
if (x == A ||
    x == C ||
    x == E ||
    x == G)
{
    ...
}

Developers are used to this type of syntax. This makes it a whole lot easier to understand when someone else is reading your code

It also expresses what you want perfectly. There's a reason this type of syntax is so widely used in existing code - because other alternatives are worse for readability.

Of course, you could wrap the condition in a function, but only if it's reusable and it logically makes sense (besides the point IMO).




回答6:


This can be done using variadic functions in c++03 as follows:

template <typename T>
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<typename T, typename T2>
bool one_equal(const T & _v1, const T2 & _v2)
{
    return _v1 == _v2;
}

template<typename T, typename T2, typename... Args>
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 <typename T1, typename T2>
bool match_one(T1 _v1, T2 _v2)
{
    return _v1 == _v2;
}

template <typename T1, typename T2, typename T3>
bool match_one(T1 _v1, T2 _v2, T3 _v3)
{
    return _v1 == _v3 || match_one(_v1, _v2);
}

template <typename T1, typename T2, typename T3, typename T4>
bool match_one(T1 _v1, T2 _v2, T3 _v3, T4 _v4)
{
    return _v1 == _v4 || match_one(_v1, _v2, _v3);
}

template <typename T1, typename T2, typename T3, typename T4, typename T5>
bool match_one(T1 _v1, T2 _v2, T3 _v3, T4 _v4, T5 _v5)
{
    return _v1 == _v5 || match_one(_v1, _v2, _v3, _v4);
}



回答7:


If not switch, maybe something like this, I didn't use it, but may be a draft to something working?

template <class ReturnType>
bool average(ReturnType expression, int count, ...)
{
  va_list ap;
  va_start(ap, count); //Requires the last fixed parameter (to get the address)
  for(int j=0; j<count; j++)
    if(expression==va_arg(ap, ReturnType))
      return true;
    return false
  va_end(ap);
}



回答8:


C++11:

template<typename T1, typename T2>
bool equalsOneOf (T1&& value, T2&& candidate) {
   return std::forward<T1>(value) == std::forward<T2>(candidate);
}

template<typename T1, typename T2, typename ...T>
bool equalsOneOf (T1&& value, T2&& firstCandidate, T&&...otherCandidates) {
   return (std::forward<T1>(value) == std::forward<T2>(firstCandidate))
     || equalsOneOf (std::forward<T1> (value), std::forward<T>(otherCandidates)...);
}

if (equalsOneOf (complexExpression, A, D, E)) { ... }

C++03:

template<typename T, typename C>
bool equalsOneOf (const T& value, const C& c) { return value == c; }

template<typename T, typename C1, typename C2>
bool equalsOneOf (const T& value, const C1& c1, const C2& c2) {
    return (value == c2) || equalsOneOf (value, c1);
}

template<typename T, typename C1, typename C2, typename C3>
bool equalsOneOf (const T& value, const C1& c1, const C2& c2, const C3& c3) {
    return (value == c3) || equalsOneOf (value, c1, c2);
}

template<typename T, typename C1, typename C2, typename C3, typename C4>
bool equalsOneOf (const T& value, const C1& c1, const C2& c2, const C3& c3, const C4& c4) {
    return (value == c4) || equalsOneOf (value, c1, c2, c3);
}

template<typename T, typename C1, typename C2, typename C3, typename C4, typename C5>
bool equalsOneOf (const T& value, const C1& c1, const C2& c2, const C3& c3, const C4& c4, const C5& c5) {
    return (value == c5) || equalsOneOf (value, c1, c2, c3, c4);
}

// and so on, as many as you need


来源:https://stackoverflow.com/questions/12240050/better-way-to-say-x-fooa-x-foob-x-fooc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!