-1

次のような istream の operator>> のオーバーロードを含む util.h/.cpp があります。

// 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++ (v. 4.6.3) で完全にうまく機能しましたが、clang (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 には問題がないのに、clang では適切な宣言が見つからないのはなぜですか。どうすればこれを修正できますか?

4

1 に答える 1

2

'file >> "[ "' を実行するファイルに util.h を含めていますか?

詳細がないと、どのような問題が発生しているのかを判断するのは困難です。私にとって、clang は次の完全なプログラムで問題なくコンパイルされます。

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

ただし、独自のオーバーロードされた演算子を提供して標準の演算子をオーバーライドすることはお勧めできないため、他の方法でこれを行うことを検討する必要があります。ルックアップのルールは難解であり、それを悪用するコードはおそらく理解と維持が困難です。

于 2012-03-13T03:43:35.307 に答える