nyarlathotep108
nyarlathotep108

Reputation: 5521

Why is the switch-case statement not allowed upon Equality-Comparable classes?

Why is a C++ class satisfying the EqualityComparable concept NOT allowed to be used in a switch-case statement? What is the rationale behind this decision?

Here follows the EqualityComparable definition:

template <class T>
concept bool EqualityComparable() { 
    return requires(T a, T b) {
        {a == b} -> Boolean; // Boolean is the concept defining a type usable in boolean context
        {a != b} -> Boolean;
    };
}

Upvotes: 0

Views: 377

Answers (2)

bolov
bolov

Reputation: 75853

The switch statement was designed with branch tables in mind. And so it requires that it operates with integer types 1). For me this is a historic reason, as I can easily see a relaxed rule where you can have any kind of comparable types, or even supply your own comparator.

Even as it is now, the compiler is not forced to use branch tables for switch (it is an implementation detail 2)), so having a switch statement that cannot create these branch tables (with non-integer types) would not be an issue in my humble opinion.


1) or enumeration type, or of a class type contextually implicitly convertible to an integral or enumeration type

http://en.cppreference.com/w/cpp/language/switch

2) in fact the compiler can do all sorts of crazy things, e.g. generate a hibrid of classic conditional jumps with multi-level branch tables.

Upvotes: 3

petersohn
petersohn

Reputation: 11730

The switch-case statement can only be used for integral types, not arbitrary equality comparable types: http://en.cppreference.com/w/cpp/language/switch

The intention of creating the switch-case construct is that it creates a jump table instead of being just a line of if-then-else constructs, which is more efficient in most cases. It may not always be more efficient in modern CPUs with branch prediction, but the language was created way before branch prediction was a thing (and is not always used even now, for example embedded CPUs like ARM).

Upvotes: 1

Related Questions