Exclude a function's return value from [[nodiscard]]

268 views Asked by At

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).
0

There are 0 answers