chkone
chkone

Reputation: 3

enum overloading operator | constexpr and runtime

I have a predeclared enum:

enum class TheEnum : std::uint32_t;

Followed by operator overloading:

constexpr TheEnum operator|(TheEnum const a, TheEnum const b)
{
    return TheEnum(std::uint32_t(a) | std::uint32_t(b));
}

With the definition:

enum class TheEnum : std::uint32_t
{
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
    D = 1 << 3,
    Val0 = TheEnum::A | TheEnum::C,
    Val1 = TheEnum::A | TheEnum::D,
    Val2 = TheEnum::B | TheEnum::D
};

I try to have the operator| constexpr and not constexpr in the same time. Currently if I add the (not constexpr):

inline TheEnum operator|(TheEnum const a, TheEnum const b)
{
    return TheEnum(std::uint32_t(a) | std::uint32_t(b));
}

My compiler said it's already defined. The constexpr allow me to do some typetrait operations, but I need the same operators for runtime evaluation.

Upvotes: 0

Views: 169

Answers (1)

walnut
walnut

Reputation: 22152

constexpr on a function means that the function may be evaluated at compile-time. It does not mean that it has to be evaluated at compile-time.

You want to declare your function constexpr and that is enough for both compile-time and run-time use.

You cannot declare two functions that only differ on constexpr and/or inline. These specifiers are not part of the function signature and therefore do not determine separate overloads of a function. Whether or not you use them, you are referring to the same entity.

Upvotes: 2

Related Questions