Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost ForEach Question

Tags:

c++

foreach

boost

Trying to use something like the below with a char array but it doesn't compile. But the example with short[] works fine. Any idea why? :)

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;
    }
like image 305
bobber205 Avatar asked May 16 '10 19:05

bobber205


1 Answers

If you go to the line in <boost/foreach.hpp> that raises the compilation error, you will see the following comment:

// **** 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") ) ...

Using boost::as_array(someChars) as shown in the comment should fix your compilation error.

like image 145
James McNellis Avatar answered Oct 06 '22 16:10

James McNellis