0

I have an enum, as given below. I want to have operator overloading for this enum,.

typedef enum E
{
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
    D = 1 << 3,
    ANY = A | B | C | D,
}
E;

//Basic version

inline E operator |(E a, E b)
{
    return static_cast<E>(static_cast<int>(a) | static_cast<int>(b));
}

//Templated version
    template<typename T, typename Types>
    inline T operator |(T var1, Types var2) {
        return static_cast<T>(static_cast<unsigned int>(var1) | static_cast<unsigned int>(var2));
    }

    template<typename T, typename... Types>
    inline T operator |(T var1, Types... var2) {
        return static_cast<T>(static_cast<unsigned int>(var2...) | static_cast<unsigned int>(var1));
    }

I am getting following errors

error: expected ')'
        return static_cast<T>(static_cast<unsigned int>(var2...) | static_cast<unsigned int>(var1));

How do I correct it.

Thanks,

TechTotie.

TechTotie
  • 127
  • 1
  • 15
  • 1
    `static_cast(var2...)` does not do what you think it does. Handwaving the compilation error away: if, for example, `var2` would be a parameter pack with three values, is `static_cast(1, 2, 4)` what you want to happen here? That would be the same as `static_cast(4)`, so all you'll get is `4`, for your troubles. BTW, `|` is not, and cannot be, a variadic overload. There's really no such thing. You "correct" it by not doing it, the "basic" version is how it should be done. – Sam Varshavchik Jul 12 '22 at 10:56
  • You are looking for `static_cast(var2)...`. But the code has other flaws, both templates match `var1 | var2` and **more importantly** you have now defined or-ing of **any** types. That is surely not what you want, what are you trying to solve? The basic version should work just fine for `A | B | C | D` – Quimby Jul 12 '22 at 11:06
  • How will the basic version work for ```A | B | C | D ``` ? ```static_cast(var2)... ```also does not work. I need to overload such that I can use enum as bit flags. – TechTotie Jul 12 '22 at 11:11
  • It works already the same way as `1+2+3+4+5`. In fact, since you are using the ordinary old enums, there is already a built-in operator so there is no need to define your own if you do not intend to provide custom behaviour. – Quimby Jul 12 '22 at 11:16
  • 1
    @TechTotie Well, it would work if you wrote the fold expression correctly but it is not needed AFAIK. Please provide a [mcve] because [this works](https://godbolt.org/z/n4h7ecoY9). – Quimby Jul 12 '22 at 11:19

1 Answers1

0

You can try with

template<typename T, typename... Ts>
inline T operator | (T var1, Ts... var2)
{
    return static_cast<T>(  (static_cast<int>(var2) | ...) |  static_cast<int>(var1));
}

But

inline E operator |(E a, E b)
{
    return static_cast<E>(static_cast<int>(a) | static_cast<int>(b));
}

also can solve your problem

hankyuan
  • 31
  • 3