简体   繁体   中英

cast variable to enum after static cast

Is it possible to cast a static_cast variable by reference into a function without having to declare an enum.

bool GetTest(enumTests &e_Test)
{
 //do something with test
}

enum enumTests
{
Test1 = 1,
Test2,
};

/* The below does NOT compile*/
int i = 1;
GetTest(static_cast<enumTests>(i));

/* The below compiles*/
enumTests e_Test = static_cast<enumTests>(i);
GetTest(e_Test);

Error

20:34: error: invalid initialization of non-const reference of type 'enumTests&' from an rvalue of type 'enumTests'

enumTests e_Test = static_cast<enumTests>(i);
GetTest(e_Test);
i = static_cast<int>(e_Test);

is the correct way.

Following would compile, but unfortunately, broke strict aliasing rule and so is UB:

static_assert(std::is_same<decltype(i), std::underlying_type_t<enumTests>>::value);
GetTest(reinterpret_cast<enumTests&>(i)); // Compile but is UB

You are trying to bind a rvalue value to a non-const reference. So you need the extra variable pass it as a lvalue. Please see https://en.cppreference.com/w/cpp/language/value_category to understand what are lvalues and rvalues.

But it's not required to static_cast explicitly as shown.

#include <iostream>

enum enumTests
{
    Test1 = 1,
    Test2,
};

bool GetTest(enumTests &e_Test)
{
    e_Test = Test2;
    return false;
 //do something with test
}

int main()
{
    int i = 1;
    auto ie = enumTests(i);
    GetTest(ie);

    std::cout << ie;
    i = ie;
    std::cout << i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM