Issue
When applied to a function, the [[nodiscard]]
attribute encourages the compiler to issue a warning if it is used in a discarded expression other than a cast to void
. Example:
[[nodiscard]] int callable_return_not_discardable(int n)
{ return n; }
int main()
{
callable_return_not_discardable(0); // warning/error:
// ignoring return value of 'int callable_return_not_discardable(int)',
// declared with attribute nodiscard [-Wunused-result]
(void) callable_return_not_discardable(0); // OK
}
Live demo on gcc-8 and clang-7.
This is nice and useful, until an additional indirection layer is added: templates:
template<class Callable>
void invoke_with_answer(Callable&& callable)
{ callable(42); }
[[nodiscard]] int callable_return_not_discardable(int n)
{ return n; }
int main()
{
invoke_with_answer(callable_return_not_discardable); // OK
}
Live demo on gcc-8 and clang-7.
My question is then:
Is it a missing feature, a consequence of what templates are or should clang and gcc be fixed to issue a warning here?
Solution
[[nodiscard]]
is not part of a function's signature or type, and not at all preserved when said function is converted to a pointer or bound to a reference. Which is exactly what your example does.
The template, for all intents and purposes cannot "see" the attribute.
Answered By - StoryTeller - Unslander Monica