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).
Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
Haozhun
  • 6,331
  • 3
  • 29
  • 50
  • 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. –  Jan 29 '21 at 19:42
  • 2
    So out of curiosity, when is "OK" not exactly OK but still OK? – StoryTeller - Unslander Monica Jan 29 '21 at 19:51
  • 8
    Have two different enums? A `[[nodiscard]] FailableResult` and a plain `NonFailableResult`? – NathanOliver Jan 29 '21 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 `.You should not declare the class as `[[nodiscard]]` if it is valid to discard it in some instances. – Mansoor Jan 30 '21 at 00: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. – Artyer Jan 30 '21 at 01:47
  • Perhaps make a wrapper function that perfectly-forward the values and explicitly discard the result for every such function (or just template-wrap them)? – user202729 Jan 30 '21 at 05:23

0 Answers0