clang如何找到声明与gcc有何不同

时间:2012-03-12 14:12:22

标签: c++ clang clang++

我有一个带有运算符重载的util.h / .cpp>>对于看起来像

的istreams
// 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 ]]

为什么clang无法找到合适的声明,而gcc没有问题。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您确定要在您执行'file&gt;&gt;的文件中包含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;
}

虽然您应该考虑以其他方式执行此操作,因为提供自己的重载运算符来覆盖标准运算符不是一个好习惯。查找规则是神秘的,滥用它们的代码可能很难理解和维护。