1

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:

  1. How embarrassing - I wrote [[nondiscard]] i.o. [[nodiscard]]
  2. When there is a typo in an attribute, the compiler usually issues a warning (attribute ignored), however no warning was issued in this case.
  3. Correcting it to [[nodiscard]] still doesn't work.
  4. 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);
}
Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
PolarBear2015
  • 745
  • 6
  • 14

1 Answers1

1

Place the attribute between the enum keyword and its name:

enum [[nodiscard]] Boolean { False = false, True = true };
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416