C++17 supports the [[nondiscard]]
attributes for functions classes(structures) and enumeration.
The following definition compiles (g++7.4.0) without producing a
"warning: ‘nondiscard’ attribute directive ignored" - So I assumed the [nondiscard]]
attribute is not ignored.
enum {False=false, True=true} [[nondiscard]] ;
However, it does not produce a warning when False or True values are discarded, (which is the goal here).
==== EDIT ====
More context to the question and: How to make a nodiscard MACRO (for class or enumeration value).
The original question as I posted has three problems:
- How embarrassing - I wrote [[nondiscard]] i.o. [[nodiscard]]
- When there is a typo in an attribute, the compiler usually issues a warning (attribute ignored), however no warning was issued in this case.
- Correcting it to [[nodiscard]] still doesn't work.
- Vittorio's syntax works.
A broader context:
I needed the [[nodiscard]] to work in a macro (#define
) because it was using FILENAME; However, [[nodiscard]] applies to a function or value returned by a function, and I had no function so the [[nodiscard]] didn't work.
I finally solved this problem using an anonymous lambda function as seen in the simplified example below.
An alternative would have been to apply [[nodiscard]] directly to lambda function. Unfortunatly C++ does not support (yet) [[nodiscard]] of lambda functions. The syntax of g() below works
//enum {False=false, True=true} [[nondiscard]] ; // wrong
//enum {False=false, True=true} [[nodiscard]] ; // wrong
enum [[nodiscard]] Boolean { False = false, True = true }; // right
#define f(x) ((x) ? True : False) // wrong
#define g(x) [](int v) {return (v ? True : False);}(x) // right
int main()
{
f(1);
g(1);
}