mardi 11 octobre 2022

Using an atomic enum class in C++11 switch statement

Not sure this is possible, but if so, how do you use an atomic enum class for a switch statement in C++11? For example,

#include <atomic>
#include <iostream>

enum class A {RED, FRUIT, APPLE};

int main(){
    std::atomic<A> myAtomicEnum;
    myAtomicEnum = A::RED;
    switch (myAtomicEnum){
        case A::RED:
            std::cout << "A::RED \n";
            break;
        default:
            break;
    }
    return 0;
}

gives a compiler error

error: multiple conversions from switch condition type
      'std::atomic<A>' to an integral or enumeration type
    switch (myAtomicEnum){

A different question using an enum class (not atomic) forced a conversion to arithmetic type using a unary +, but you can't pass an std::atomic<A> to the unary +. I don't receive any errors using a non-atomic enum class and not using a unary +, e.g.

#include <iostream>

enum class A {RED, FRUIT, APPLE};

int main(){
    A myEnum = A::RED;
    switch (myEnum){
        case A::RED:
            std::cout << "A::RED \n";
            break;
        default:
            break;
    }
    return 0;
}

which outputs A::RED as expected.

The context of the problem is that I have a class with a member that may be read/written to by multiple threads and a switch statement using that member. I have a workaround using mutex-es so that I have well-defined behavior but would like to use atomic if possible.

Aucun commentaire:

Enregistrer un commentaire