Kar*_*aru 10 c++ foreach c++11
有没有办法不在基于范围的for循环中"使用"循环变量,还避免编译器警告它未被使用?
对于上下文,我正在尝试执行以下操作.我已经"将警告视为错误",并且我宁愿不做一个黑客,就像强迫变量被某个地方毫无意义地提到"使用"一样.
size_t getSize(const std::forward_list &list)
{
size_t count = 0;
for (auto & : list) // compile error, but if i do "auto &i" here, MSVC
// complains (reasonably) that i is unused
{
++count;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
我知道还有其他方法可以做到这一点,但是为了论证,我需要使用基于范围的for循环.
您始终可以明确声明该变量在循环体中保证未使用:
ptrdiff_t size( std::forward_list const& list )
{
ptrdiff_t count = 0;
for( auto& dummy : list )
{
(void) dummy; struct dummy; // Wrap this in a macro if you want.
// Here everybody including compiler knows that dummy isn't used and can't be used.
++count;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
然而,上述内容远不如简单地使用普通for循环.
更不用说简单地打电话了size.
您可以定义一个宏:
#if defined(__GNUC__)
# define UNUSED __attribute__ ((unused))
#elif defined(_MSC_VER)
# define UNUSED __pragma(warning(suppress:4100))
#else
# define UNUSED
#endif
...
for (auto &dummy UNUSED : list)
{
++count;
}
...
Run Code Online (Sandbox Code Playgroud)
它适用于GCC和CLANG(不太确定MSVC ......我似乎记得MSVC将禁用文件其余部分的警告).
也:
template<class T> void unused(const T &) {}
...
for (auto &dummy : list)
{
unused(dummy);
++count;
}
...
Run Code Online (Sandbox Code Playgroud)
适用于所有编译器,不应有任何开销(Mailbag:关闭编译器警告).
Boost头<boost/core/ignore_unused.hpp>(Boost> = 1.56)为了相同的目的定义了函数模板boost::ignore_unused().
使用C++ 11也是std::ignore一个不错的选择:
{
std::ignore = dummy;
// ...
}
Run Code Online (Sandbox Code Playgroud)
类似的问题:
PS C++ 17 似乎获得了一个[[maybe_unused]]属性来提供一种声明未使用变量的标准方法.
| 归档时间: |
|
| 查看次数: |
2785 次 |
| 最近记录: |