基于范围的for循环中未命名的循环变量? [英] Unnamed loop variable in range-based for loop?

查看:168
本文介绍了基于范围的for循环中未命名的循环变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方法不能在基于范围的for循环中使用循环变量,但也避免编译器对它未使用的警告?



,我想做一些像下面的事情。我有治疗警告作为错误启用,我宁愿不做一个黑客,强迫变量被使用无意义地提到它在某个地方。

  size_t getSize(const std :: forward_list& list)
{
size_t count = 0;
for(auto&:list)//编译错误,但是如果我在这里做auto& i,MSVC
//(合理地)抱怨我是未使用
{
++ count;
}
return count;
}

我知道还有其他方法可以做到这一点,我需要使用基于范围的for循环。

解决方案

你可以明确地声明变量在循环体:

  ptrdiff_t size(std :: forward_list const& list)
{
ptrdiff_t count = 0;
for(auto& dummy:list)
{
(void)dummy; struct dummy; //如果你想要在一个宏包装。
//这里每个人都包括编译器知道虚拟没有使用,不能使用。

++ count;
}
return count;
}

然而,上述情况远比简单使用普通的



更不用说简单地调用 size p>

Is there any way to not "use" the loop variable in a range-based for loop, but also avoid compiler warnings about it being unused?

For context, I'm trying to do something like the following. I have "treat warnings as errors" enabled, and I'd rather not do a hack like forcing the variable to be "used" by pointlessly mentioning it somewhere.

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;
}

I know there are other ways to do this, but let's say for argument's sake that I need to use a range-based for loop.

解决方案

You can always state explicitly that the variable is guaranteed unused in the loop body:

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;
}

The above is however much less clear than simply using an ordinary for-loop.

Not to mention simply calling size.

这篇关于基于范围的for循环中未命名的循环变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆