C++ Operator Overloading: Bitwise Operators & If-Check

Started by
15 comments, last by AzureBlaze 8 years, 9 months ago

Hey guys!

Since I need to use flags, but don't want to restrict myself to a maximum number of flags (Depending on the type I use: char, int, etc), I thought about creating some kind of templated<T> class storing T's in a list, on which operators can be used to make it look like standard C++ Bitwise flags.

(First things first: I don't know much about all that bitwise stuff)

Let's name my class "UFlag". How I want to be able to use it:


//Long way
UFlag<int> flag;
flag | 10 | 55;
if(flag & 10);
    //do stuff. This will be true, obviously.

//But also on the fast way:
myMethodTakingUFLAGasArgument(UFlag<int> | 10 | 55) //Somehow like this, so that I don't have to declare my variable first...

...

void myMethodTakingUFLAGasArgument(UFlag<int> f){
    UFlag<int> uf | 10; //I want also to be able to declare it like this... Saves one line.
    if(f & uf) ;//do stuff. should be true with the example-argument above.
    if(f & 55) ;//do stuff. should be true with the example-argument above.
}

Here is what I have right now: https://ideone.com/7jtnep

Unfortunately, not everything is working yet.

1 - I have not figured out yet how to apply the |/& operators in the same line as where I create the object.

2 - if checking doesnt work yet, as UFlag isnt a boolean.

How do I solve these two problems?

Kind regards,

Flyverse

Edit: Solved Problem#2.

Advertisement

1. Normally the only operator that will return a reference to itself is an assignment operator like = or +=. The rest should take constant parameters (including "this") and return a new object. "c = a + b" does not alter the content of a or b.

UFlag<T> operator |(const UFlag<T> &b) const

should do the trick.

2. Implement explicit operator bool() const;

You might want to look at std::bitset. Either because it does everything you want already or as an inspiration.

operator bool ()const

{

... your boolean logic

}

it's the same way you can cast anything to another, i.e



struct Mask
{
  Mask(int v): 
  value(v)
  {
  }
  operator int()const{ return value;}

private:

int value;
};

 void SomeFunction(int i)
{

}

int main()
{
  Mask MyMask(5);

  SomeFunction(MyMask);

}
First, let's address some problems:

You can't do this, C/C++ grammar doesn't work this way at all, and not even horrible hacks can make it work:
UFlag<int> uf | 10; //I want also to be able to declare it like this... Saves one line.
Try:
UFlag<int> uf{10};
Second, your conditional idiom is slightly problematic even with plain integers, unless you particularly like getting lots of warnings:
    if(f & uf) ;//do stuff. should be true with the example-argument above.
    if(f & 55) ;//do stuff. should be true with the example-argument above.
Prefer:
if((f & uf) != uf)
Alright, on to the main event.

I don't like using complex wrapper types for flags. We have enums. Let's use them. On some calling conventions, you'll actually be penalized for using classes/structs where you could have used a primitive type (even small structs may always be passed via the stack and never registers), so it's doubly important that we stick to plain enums if they'll ever be used anywhere perf-sensitive in multi-platform code.

C++11 strong enums have further advantages (you can specify the size explicitly, and they're namespaced). However, since you can't use operators like | and & with C++11 strong enums, but we want them for flags, but we _only_ want them enabled for flags, we need a new type trait.

You could use a wrapper type and just adapt the type traits I have here to simply checking against your wrapper type if you prefer the wrapper or just dislike type traits.

Here's my "flagset.h" (minus some helper functions that I rarely use) that I made for my personal toys/experiments:

// Sean Middleditch <sean@middleditch.us> - 2014
// This is free and unencumbered software released into the public domain.
// 
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
// 
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// 
// For more information, please refer to <http://unlicense.org/>

#if !defined(_guard_STLX_FLAGSET_H)
#define(_guard_STLX_FLAGSET_H)
#pragma once

#include <type_traits>

namespace stlx
{
	template <typename T> struct is_flagset;
	template <typename T> constexpr T bitmask(T);
}

/// Specialize to indicate that an enum is a flag set (and should be combinable).
/// @tparam T the enumeration to mark.
template <typename T> struct stlx::is_flagset : std::false_type {};

/// Set a given bit 1, all other bits to 0.
/// @param bit the bit to set.
template <typename T>
constexpr T stlx::bitmask(T bit) { return T(1) << bit; }

// Operators for flagsets.
template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E operator|(E lhs, E rhs) { return E(std::underlying_type_t<E>(lhs) | std::underlying_type_t<E>(rhs)); }

template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E operator&(E lhs, E rhs) { return E(std::underlying_type_t<E>(lhs) & std::underlying_type_t<E>(rhs)); }

template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E operator^(E lhs, E rhs) { return E(std::underlying_type_t<E>(lhs) ^ std::underlying_type_t<E>(rhs)); }

template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E& operator|=(E& lhs, E rhs) { return lhs = E(std::underlying_type_t<E>(lhs) | std::underlying_type_t<E>(rhs)); }

template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E& operator&=(E& lhs, E rhs) { return lhs = E(std::underlying_type_t<E>(lhs) & std::underlying_type_t<E>(rhs)); }

template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E& operator^=(E& lhs, E rhs) { return lhs = E(std::underlying_type_t<E>(lhs) ^ std::underlying_type_t<E>(rhs)); }

template <typename E, typename = std::enable_if_t<stlx::is_flagset<E>::value>>
constexpr E operator~(E rhs) { return E(~std::underlying_type_t<E>(rhs)); }

#endif // defined(_guard_STLX_FLAGSET_H)
And some example usage modeled from a virtual file system wrapper I have:

enum class EFileMode : std::uint16_t
{
	None = 0,
	Read = stlx::bitmask(0U),
	Write = stlx::bitmask(1U),
	Create = stlx::bitmask(2U),
	Exclusive = stlx::bitmask(3U),
	Truncate = stlx::bitmask(4U),
	MakeDir = stlx::bitmask(5U),

	WriteNew = Write|Create|Truncate|MakeDir,
};
namespace stlx
{
	template<> struct is_flagset<EFileMode> : std::true_type {};
}

File OpenFile(string_view path, EFileMode mode) {
  // silly example
  if ((mode & (EFileMode::Truncate | EFileMode::Create)) != EFileMode::None);
    mode &= EFileMode::Write;
  ...
  return file;
}

auto file = OpenFile(path, EFileMode::Write | EFileMode::Create | EFileMode::Truncate);

Sean Middleditch – Game Systems Engineer – Join my team!

Oh yeah, another advantage of using enums is that good IDEs (like Visual Studio) will properly visualize them in the debugger view.

They even innately visualize flags of enum values. So
EFileMode mode = EFileMode::Create | EFileMode::Truncate
will actually show up in the watch window as
mode  Create|Truncate
You can't get your wrapper type to do that properly.

Sean Middleditch – Game Systems Engineer – Join my team!

Second, your conditional idiom is slightly problematic even with plain integers, unless you particularly like getting lots of warnings:


if(f & uf) ;//do stuff. should be true with the example-argument above.
Prefer:

if((f & uf) != uf)

Why is the second preferred?


unsigned f  = (1 | 2 | 4 | 8);
unsigned uf = 4;

(f & uf) = uf
uf is non-zero
if(non-zero) = true

Second, your conditional idiom is slightly problematic even with plain integers, unless you particularly like getting lots of warnings:


if(f & uf) ;//do stuff. should be true with the example-argument above.
Prefer:

if((f & uf) != uf)

Why is the second preferred?

I suspect it was supposed to be (f & uf) != 0, since the other version is definitely not equivalent. It prevents the implicit cast from unsigned to bool and all the potential compiler warnings that come with it (in VS it's usually something about runtime performance).

f@dzhttp://festini.device-zero.de

I suspect it was supposed to be (f & uf) != 0, since the other version is definitely not equivalent. It prevents the implicit cast from unsigned to bool and all the potential compiler warnings that come with it (in VS it's usually something about runtime performance).

I do not know what his intention was, however typically if you're testing flags and you want to ensure that all of the flags you are testing are set, you want (flags & flagsToTestFor) == something, as otherwise only having some of the flags in flagsToTestFor set can still return non-zero.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Maybe I missed the objections but... why do you have to use flags and masks? Unless I have a lower-level component requiring it, I'd stay away from them.

Previously "Krohm"

This topic is closed to new replies.

Advertisement