Common Data-type Operator Overloading

Hey there,
I was wondering how you would overload an operator for Common Data-types like "char" and "int".
You may ask...
"Why would you want to do that?"

I often use bool arrays to create a multilevel-trigger-systems, when iterating over multiple containers or waiting for two events to occur at the same time.

For example:
I would define..
bool trigger[2] = {0, 0};

And when doing work via a loop,
I use it like so:
while(trigger[0] != 1 && trigger[1] != 1)

You can probably see where I'm going with this.
I want to be able to use my bool array with the "!" operator.
So if "trigger == 0" (as a whole), it returns false.

How can I achieve this?


SIDE NOTE:
Can you create custom operators?
Say if I wanted to create "or-gates" or "xor-gates" etc.
You may want to consider using std::bitset<>
http://en.cppreference.com/w/cpp/utility/bitset

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <bitset>
#include <string>

int main()
{
    std::bitset<21> trigger( "10110111000111001" ) ;
    std::cout << trigger << '\n' ; // 000010110111000111001

    trigger[5] = false ;
    trigger[10] = true ;
    trigger[20].flip() ;
    std::cout << trigger << '\n' ; // 100010110111000011001

    std::cout << std::hex << std::showbase << trigger.to_ulong() << '\n' ; // 0x116e19
    trigger = 0xabcdef ;
    std::cout << trigger << '\n' // 010111100110111101111
              << trigger.to_ulong() << std::dec << '\n' ; // 0xbcdef

    std::string flags = "flags: " + trigger.to_string() ;
    std::cout << flags << '\n' ; // flags: 010111100110111101111

    // some of the bits are set
    if( trigger.any() ) std::cout << "some of the bits are set\n" ;
    else std::cout << "no bit is set\n" ;

    // not all the bits are set
    if( trigger.all() ) std::cout << "all the bits are set\n" ;
    else std::cout << "not all the bits are set\n" ;

    // 15 of 21 bits are set
    std::cout << std::dec << trigger.count() << " of " << trigger.size() << " bits are set\n" ;

    trigger = 0 ;
    // no bit is set
    if( trigger.any() ) std::cout << "some of the bits are set\n" ;
    else std::cout << "no bit is set\n" ;

    trigger = ~trigger ;
    // all the bits are set
    if( trigger.all() ) std::cout << "all the bits are set\n" ;
    else std::cout << "not all the bits are set\n" ;
}

http://coliru.stacked-crooked.com/a/d8a68d58b35a428c
There is no way to change the meaning of the operators for built-in types: at least one argument of an overloaded operator must be a class/struct/union or enumeration

If you use std::bitset<2>, you could be testing it with if(trigger.any()) or similar:

http://en.cppreference.com/w/cpp/utility/bitset/all_any_none
Thanks. I'll explore the bitset option.
Topic archived. No new replies allowed.