2010-05-16 9 views
8

Provare a utilizzare qualcosa come il seguito con un array di caratteri ma non viene compilato. Ma l'esempio con short [] funziona bene. Qualche idea del perché? :)Boost ForEach Domanda

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

risposta

17

Se si va alla linea in <boost/foreach.hpp> che genera l'errore di compilazione, si vedrà il seguente commento:

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

Utilizzando boost::as_array(someChars) come indicato nel commento dovrebbe risolvere il tuo errore di compilazione.

+0

Molte grazie. Era troppo veloce per postare in SO. :) – bobber205