5

I want to mark a class as nodiscard, but exclude the return value of a certain function from the nodiscard requirement. This is my goal:

enum class [[nodiscard]] Result { OK1, OK2, ERROR, }; [[ok-to-discard]] // This attribute is made up to illustrate my need. Result doSomethingThatCannotFail() { // The function can return OK1 or OK2, but the caller may or may not care. // The function cannot return ERROR. // Therefore, it's OK to discard this particular Result return value, // even though in general Result should not be ignored. } 

I do not believe it's a good idea to add ok-to-discard at every call site (which is covered by How can I intentionally discard a [[nodiscard]] return value?):

  • There are many callsites. It would be nice to avoid adding ok-to-discard everywhere.
  • Maybe one day I'll change the function, and it will no longer be OK to discard. It would be preferable to keep the ok-to-discard instruction with the function so that I can drop it when that happens (and get compiler warnings/errors).
6
  • 1
    And why don't you want to add [[nodiscard]] to every function? Seems to be as troublesome as what you are doing right now. PS: I realized that you probably think that [[nodiscard]] is only for types...It is not. Commented Jan 29, 2021 at 19:42
  • 2
    So out of curiosity, when is "OK" not exactly OK but still OK? Commented Jan 29, 2021 at 19:51
  • 8
    Have two different enums? A [[nodiscard]] FailableResult and a plain NonFailableResult? Commented Jan 29, 2021 at 20:02
  • 1
    It's just a warning so I would ignore and put a comment. Or you can use compiler pragmas to hid it, like #pragma GCC diagnostic ignored <warning_to_ignore>.You should not declare the class as [[nodiscard]] if it is valid to discard it in some instances. Commented Jan 30, 2021 at 0:29
  • 1
    A somewhat terrible solution: Result is [[nodiscard]], but const Result& isn't, so you can return references to static constexpr variables defined in the function instead. Commented Jan 30, 2021 at 1:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.