2010-05-16 180 views
8

試圖使用類似下面的字符數組,但它不編譯。但短[]的例子工作正常。任何想法爲什麼? :)提升對於每個問題

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

回答

17

如果你去在<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)如圖所示的評論應該解決您的編譯錯誤。

+0

非常感謝。太快,無法發佈到SO。 :) – bobber205 2010-05-16 22:54:02