Search code examples
c++c++11bitset

best way to set a bitset with boolean values


Suppose I have 3 bool type values

bool canwalk=true;
bool cantalk=false;
bool caneat=false;

I would like to set a bitset denoting the three

std::bitset<3> foo;

How can I construct a bitset using the boolean values? I want to do something like this

 std::bitset<3> foo(canWalk,cantalk,caneat); //giving me 100

Solution

  • Following the example of Shivendra Agarwal, but using the constructor that receive an unsigned long long, I propose the following variadic template function (to be more generic)

    template <typename ... Args>
    unsigned long long getULL (Args ... as)
     {
       using unused = int[];
    
       unsigned long long ret { 0ULL };
    
       (void) unused { 0, (ret <<= 1, ret |= (as ? 1ULL : 0ULL), 0)... };
    
       return ret;
     }
    

    that permit the initialization of foo as follows

    std::bitset<3> foo{ getULL(canwalk, cantalk, caneat) };
    

    This works only if the dimension of the std::bitset isn't grater of the number of bits in an unsigned long long (with 3 whe are surely safe).

    The following is a full working example

    #include <bitset>
    #include <iostream>
    
    template <typename ... Args>
    unsigned long long getULL (Args ... as)
     {
       using unused = int[];
    
       unsigned long long ret { 0ULL };
    
       (void) unused { 0, (ret <<= 1, ret |= (as ? 1ULL : 0ULL), 0)... };
    
       return ret;
     }
    
    int main()
     {
       bool canwalk=true;
       bool cantalk=false;
       bool caneat=false;
    
       std::bitset<3> foo{ getULL(canwalk, cantalk, caneat) };
    
       std::cout << foo << std::endl;
     }