【问题标题】:Boost ForEach Question提升 ForEach 问题
【发布时间】:2010-05-16 19:10:39
【问题描述】:

尝试使用类似下面的内容和 char 数组,但无法编译。但是带有 short[] 的示例可以正常工作。知道为什么吗? :)

char someChars[] = {'s','h','e','r','r','y'};
    BOOST_FOREACH(char& currentChar, someChars)
    {

    }


short array_short[] = { 1, 2, 3 };
    BOOST_FOREACH( short & i, array_short )
    {
        ++i;
    }

【问题讨论】:

    标签: c++ boost foreach


    【解决方案1】:

    如果您转到<boost/foreach.hpp> 中引发编译错误的行,您将看到以下注释:

    // **** READ THIS IF YOUR COMPILE BREAKS HERE ****
    //
    // There is an ambiguity about how to iterate over arrays of char and wchar_t. 
    // Should the last array element be treated as a null terminator to be skipped, or
    // is it just like any other element in the array? To fix the problem, you must
    // say which behavior you want.
    //
    // To treat the container as a null-terminated string, merely cast it to a
    // char const *, as in BOOST_FOREACH( char ch, (char const *)"hello" ) ...
    //
    // To treat the container as an array, use boost::as_array() in <boost/range/as_array.hpp>,
    // as in BOOST_FOREACH( char ch, boost::as_array("hello") ) ...
    

    使用注释中显示的boost::as_array(someChars) 应该可以修复您的编译错误。

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多