未命名的命名空间和iostream导致“!=非法操作”

时间:2011-12-13 11:59:01

标签: c++ functional-programming g++ iostream sunos

#include <functional>
#include <iostream>

struct A {
    friend bool operator==( const A & a, const A & b ){
        return true;
    }
};

namespace {
    bool operator!=( const A &a, const A & b){
        return !(a==b);
    }
}

int main(int argc, char **argv) {
    std::not_equal_to<A> neq;
    A a;

    bool test = neq(a, a);

    return test ? 0 : 1;
}

这在CC(SunOs编译器)上失败了:

Error: The operation "const A != const A" is illegal.
"tempcc.cpp", line 16:     Where: While instantiating "std::not_equal_to<A>::operator()(const A&, const A&) const".
"tempcc.cpp", line 16:     Where: Instantiated from non-template code.

g++上:

/usr/local/include/c++/3.3.2/bits/stl_function.h: In member function `bool std::not_equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = A]':
tempcc.cpp:16:   instantiated from here
/usr/local/include/c++/3.3.2/bits/stl_function.h:183: error: no match for 'operator!=' in '__x != __y'

但是,如果我删除行#include <iostream>,它会编译并运行得很好。有谁敢解释这个?

2 个答案:

答案 0 :(得分:0)

根据Comeau的说法,这不合法 - 编译器在你不#include <iostream>时构建它可能是真正的错误,而不是相反的方式(或者至少在分歧方面)解释):

"stl_function.h", line 99: error: no operator "!=" matches these operands
            operand types are: const A != const A
    bool operator()(const _Tp& __x, const _Tp& __y) const { return __x != __y; }
                                                                       ^
          detected during instantiation of "bool
                    std::not_equal_to<_Tp>::operator()(const _Tp &, const _Tp
                    &) const [with _Tp=A]" at line 19 of "ComeauTest.c"

"ComeauTest.c", line 10: warning: function "<unnamed>::operator!=" was declared but
          never referenced
      bool operator!=( const A &a, const A & b){
           ^

有意义的是,这不构建 - 将operator!=置于未命名的命名空间中仍然将其放在与::不同的命名空间中,并且我不完全确定为什么g ++在没有命名空间的情况下构建它iostream包括 - 如果你看一下g ++的预处理器输出,它没有做任何重新排序代码或任何这样的废话的错误,当然iostream没有为operator!=定义{ {1}}。

我没有方便的C ++标准副本,但IBM的this link至少验证了未命名的命名空间与全局命名空间不能很好地混合的说法,解释了为什么你找不到A您已定义。

您还可以在Anonymous Namespace Ambiguity中找到一些有用的信息。

答案 1 :(得分:0)

问题是<functional>还会从tupleutility中提取干扰查找的几个模板。

如果你要删除它,例如通过仅在GCC中包含<bits/stl_function.h>,那么没有问题,尽管当然不是真正的解决方案。如果您需要谓词,我想您无法实现自己的operator!=()或为std::not_equal_to添加明确的专门化。

但是,如果您不需要使用not_equal_to谓词,则可以通过删除所有自定义代码并添加以下内容来完全解决问题:

#include <utility>
using namespace std::rel_ops;

bool test = a != a;