Thread: Set of binary properties. Vector of bool?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Then use bitwise operators to set named bits that you then inspect so as to populate the struct of bools. Or instead of bitwise operations, you can use function chaining to set the members of the struct of bools directly in a consistent manner.

    EDIT:
    Actually, if you are going to use bitwise operations, it probably doesn't make sense to translate it into a struct of bools. You might as well go with an unsigned int or std::bitset. std::vector<bool> probably isn't that good a fit either since you have a fixed number of flags. The key to overcoming "I don't see the labels, just the indices" is to combine these bitwise operations with an enum of the properties.

    If you do go with a struct of bools, then the function chaining thing should fit the bill quite well, e.g.,
    Code:
    struct Flags
    {
        bool red = false;
        bool green = false;
        bool thin = false;
        bool young = false;
    
        Flags& Red()
        {
            red = true;
            return *this;
        }
    
        Flags& Green()
        {
            green = true;
            return *this;
        }
    
        Flags& Thin()
        {
            thin = true;
            return *this;
        }
    
        Flags& Young()
        {
            young = true;
            return *this;
        }
    };
    
    // ...
    
    MyClass Example(Flags().Red().Green().Young());
    Last edited by laserlight; 09-26-2019 at 06:06 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bool vector operations - a more efficient way needed
    By baxy in forum C++ Programming
    Replies: 7
    Last Post: 11-08-2015, 03:50 AM
  2. bool typedef and binary compatibility
    By BattlePanic in forum C Programming
    Replies: 2
    Last Post: 05-08-2008, 08:04 AM
  3. How get bool's from std::vector<bool>
    By 6tr6tr in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2008, 05:24 AM
  4. vector<bool> push_back
    By ygfperson in forum C++ Programming
    Replies: 4
    Last Post: 03-05-2003, 08:48 PM

Tags for this Thread