Skip to content

Making CRGB::operator bool() explicit would be useful #819

Closed

Description

@ssilverman

It's easy to assign CRGB to an integral value for a number of reasons, however, if you aren't careful to use your own, for example, uint32 toColor function, the bool() operator is used.

My suggestion is to make CRGB::operator bool() explicit.

Ref: See mention of the Safe Bool idiom mentioned in the "Explicit Conversion Operators (C++11)" section at: https://stackoverflow.com/a/16615725.

I find myself doing this:

// Extends FastLED's CRGB to add a uint32_t conversion and make
// `operator bool()` explicit.
class MyCRGB : public CRGB {
 public:
  MyCRGB() : CRGB(){};
  explicit MyCRGB(const CRGB &rhs) : CRGB(rhs){};
  explicit MyCRGB(const CHSV &rhs) : CRGB(rhs) {}
  explicit MyCRGB(uint32_t c) : ::CRGB(c) {}
  ~MyCRGB() = default;

  MyCRGB &operator=(const CRGB &rhs) {
    CRGB::operator=(rhs);
    return *this;
  }

  MyCRGB &operator=(const CHSV &rhs) {
    CRGB::operator=(rhs);
    return *this;
  }

  explicit operator bool() const {
    return CRGB::operator bool();
  }

  // Converts a CRGB to a 32-bit colour having an alpha of 255.
  explicit operator uint32_t() const {
    return uint32_t{0xff000000} |
           (uint32_t{r} << 16) |
           (uint32_t{g} << 8) |
           uint32_t{b};
  }
};

Activity

  1. kriegsman commented on Jun 17, 2019

    @kriegsman
    Member

    Thanks for the suggestion; I think it's a great idea.
    I want to think about how and in what ways this is going to change the (compile-time or run-time) behavior of existing code, but overall I really like this idea.

  2. self-assigned this
    on Jun 17, 2019
  3. ssilverman commented on Jun 17, 2019

    @ssilverman
    ContributorAuthor

    Yes, a large enough set of users means even testing things that "shouldn't" have an effect. 😀

    Having said that, I'm willing to bet adding explicit here will find usage errors in code that attempts to assign to any integral value, having an unintended consequence.

  4. added a commit that references this issue on Jul 20, 2023
  5. added a commit that references this issue on Aug 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions