(10): warning C4189: 'n': local variable is initialized but not referenced (22): note: see reference to function template instantiation 'std::ostream &operator <<>(std::ostream &,const std::tuple<> &)' being compiled
gcc 和 clang 不会发出任何警告。
由于我也使用了Werror//we,我想摆脱这个警告(如果可能的话,不使用#pragma)。
为什么 MSVC 的行为会这样?
我如何摆脱这个警告(在 lambda 内部添加 if constexpr (sizeof...(Ts)>0) 会有帮助吗?
英文:
I have a warning about unreferenced variable when using std::apply on an empty tuple.
This snippet, inspired from std::apply cppreference shows the issue:
Live<br>
MSVC, with /permissive-, outputs the following warning with the very last line:
> <source>(10): warning C4189: 'n': local variable is initialized but not referenced<br>
> <source>(22): note: see reference to function template instantiation 'std::ostream &operator <<<>(std::ostream &,const std::tuple<> &)' being compiled
gcc and clangs do not issue anything.
As I'm using also Werror//we I'd like to get rid of this warning (without using pragma, if possible).
Why does msvc behaves like that?
How can I get rid of this warning (adding a if constexpr (sizeof...(Ts)>0) inside the lambda?)?
if constexpr 更冗长,但在 n 实际未使用时更明确。<br>
奇怪的是,我找不到一种方法来让 gcc 和 clang 发出类似的警告。
英文:
Proposing an answer from the comments.
From fold expression cppreference:
> Explanation
...<br>
When a unary fold is used with a pack expansion of length zero, only the following operators are allowed:
>
> 1) Logical AND (&&). The value for the empty pack is true
> 2) Logical OR (||). The value for the empty pack is false<br>
> 3) The comma operator (,). The value for the empty pack is void()
emphasis mine.
Thus in ((os << tupleArgs << (++n != sizeof...(Ts) ? ", " : "")), ...);, if the tuple is empty, the expression becomes void();, resulting to n not being used, thus msvc is right to issue a warning.
Then, this warning can be silenced by a mere [[maybe_unused]] std::size_t n{0};.
The if constexpr is more verbose but also more explicit with respect to when n is actually unused.<br>
Strangely enough, I couldn't find a way to make gcc and clang issue a similar warning.
评论