2012-03-12 28 views
-1

我有istreams的util.h /的.cpp與運營商的重載>>,它看起來像如何鏗鏘從GCC的不同之處是如何找到的聲明

// util.h 
// 
// ... lots of stuff ... 

std::istream& operator>>(std::istream& is, const char *str); 
std::istream& operator>>(std::istream& is, char *str); 

而且

// util.cpp 
// 
// lots of stuff again 
//! a global operator to scan (parse) strings from a stream 
std::istream& operator>>(std::istream& is, const char *str){ 
    parse(is, str); return is; 
} 
//! the same global operator for non-const string 
std::istream& operator>>(std::istream& is, char *str){ 
    parse(is, (const char*)str); return is; 
} 

在其他一些文件我用這種構造是這樣的:

std::istream file; 
char *x, *y; 

// opening and allocating space for strings comes here 

file >> "[ " >> x >> "," >> y >> " ]"; 

這個工作非常順利地使用GCC/G ++,但現在我想用c(v 4.6.3)。郎(V 3.0),並得到了錯誤的陳述,即適當的操作符重載無法找到:

clang -ferror-limit=1 -g -Wall -fPIC -o ors.o -c ors.cpp 
ors.cpp:189:21: error: invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'const char [2]') 
    file >> "[ " >> x >> "," >> y >> " ]"; 
    ~~~~^~~~~ 
/usr/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/istream:121:7: note: candidate function 
    not viable: no known conversion from 'const char [2]' to '__istream_type &(*)(__istream_type &)' for 1st argument; 
    operator>>(__istream_type& (*__pf)(__istream_type&)) 
[[ lots of other possible candidates from the stl ]] 

爲什麼鐺無法找到相應的聲明,而GCC有沒有問題。我怎樣才能解決這個問題?

+0

你能告訴我們你在每個文件中包含了什麼嗎?也許g ++的實現是包含clang不是的另一個頭。 – 2012-03-12 14:15:45

+3

當您詢問有關編譯器不同行爲的問題時,始終建議您發佈一個小型可編譯代碼示例。 – 2012-03-12 14:17:43

+0

我將嘗試獲得最小的可編譯示例。 – hildensia 2012-03-12 14:18:08

回答

2

你確定你在包含util.h文件的地方做'文件>>「[」'?

沒有更多的細節,很難說出你遇到了什麼問題。對我來說,鐺編譯就好用下面的完整的程序:

#include <iostream> 
#include <sstream> 

std::istream& operator>>(std::istream& is, const char *str); 
std::istream& operator>>(std::istream& is, char *str); 

int main() { 
    std::stringstream file("tmp"); 
    char *x, *y; 

    // opening and allocating space for strings comes here 

    file >> "[ " >> x >> "," >> y >> " ]"; 
} 


// util.cpp 
// 
// lots of stuff again 

void parse(std::istream& is, const char *str) {} 

//! a global operator to scan (parse) strings from a stream 
std::istream& operator>>(std::istream& is, const char *str){ 
    parse(is, str); return is; 
} 
//! the same global operator for non-const string 
std::istream& operator>>(std::istream& is, char *str){ 
    parse(is, (const char*)str); return is; 
} 

雖然你應該考慮一些其他的方式做這個,因爲提供自己的重載運算符重載一個標準是不是一個好的做法。查找規則是神祕的,濫用它們的代碼可能難以理解和維護。

+0

是的,這個最小的例子編譯。因此,我們的文件中可能還有一些其他的東西神奇地掩蓋了操作符重載。 代碼庫實際上是舊的,所以改變這個運算符的重載會破壞很多。 – hildensia 2012-03-14 11:47:30

+0

@hildensia如果你能提供一個能夠再現問題的(小)程序,我可能會提供更好的答案。 – bames53 2012-03-14 16:09:56

+0

我會試着舉個例子,但可能需要一些時間,因爲我現在已經被佔用了。 – hildensia 2012-03-14 16:12:28