Quick Q: std::ignore for ignoring unused variable

Quick A: While in theory possible, it is not the intended usage and other solutions exist.

Recently on SO:

std::ignore for ignoring unused variable

std::ignore may work but it is intended to be used for tuples. So you need to include the tuple header and who knows what operations are done for the assignment. This also may break in another c++ version because it was never documented to be used that way.

A better way for this is the C++17 attribute [[maybe_unused]]

void func([[maybe_unused]] int i)
{
}

It places the declaration right at the variable declaration, so you don't have to declare it in an extra line/statement.

The same can be used for local (and local-static) variables

...
[[maybe_unused]] static int a = something();
...

And also for many more:

Appears in the declaration of a class, a typedef­, a variable, a non­static data member, a function, an enumeration, or an enumerator. If the compiler issues warnings on unused entities, that warning is suppressed for any entity declared maybe_unused.

See http://en.cppreference.com/w/cpp/language/attributes

As for the people concerned that you can still use the variables after you declare them unused:

Yes, this is possible but (at least with clang) you will get warnings in case you use maybe_unused declared variables.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.