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).
[[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.[[nodiscard]] FailableResultand a plainNonFailableResult?#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.Resultis[[nodiscard]], butconst Result&isn't, so you can return references tostatic constexprvariables defined in the function instead.