Pass enum with class enum reference

I have the following code , which, it seems to me, should compile, but does not work.

#include <cstdint> typedef uint8_t testtype; enum testenum : uint8_t { }; void foo(uint8_t& v) {} int main() { testtype bar; foo(bar); testenum baz; foo(baz); return 0; } 

I get the following error:

 prog.cpp:15:9: error: invalid initialization of non-const reference of type 'uint8_t& {aka unsigned char&}' from an rvalue of type 'uint8_t {aka unsigned char}' foo(baz); 

In my opinion, this should work because everything has the same base type (uint8_t). The typedef'ed variable can be passed to the foo function, but the enum (which has the uint8_t enum uint8_t ) cannot.

In my project, this means that I cannot pass all my enumerations into one overloaded function - it seems that I need to create an overload for every possible enumeration.

Is there an elegant way to get this for compilation, or do I need to pass enum through a second variable that I can pass by reference?

+6
source share
1 answer

Enumerations in C ++ are more than just applying a name to an integer; for this we have const int variables. Enums conceptually represent an integer that should only store one of many specific values.

Typedefs are aliases; they are the same in all respects to this type. Enumerations are different types. They use their base types, and they can be converted to it, but they are not the same type as their base types.

Thus, a reference to uint8_t is not the same as a reference to an enumeration, even if this enumeration uses uint8_t as its base type. Therefore, converting from a link from enum to a reference-to-base type is an illegal conversion, as well as a violation of strict aliases.

You can pass it by value, since non-class enumerations are implicitly converted to their base types. And you can bypass const& , since an implicit conversion can create a temporary one to populate this link. But you cannot pass an enumeration to a function that refers to a const reference to an integer.

+9
source

All Articles