c++ - 未命名的命名空间和 iostream 导致 "!= being illegal operation"

标签 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>它编译并运行得很好。有谁敢解释一下吗?

最佳答案

根据 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 的情况下构建它include - 如果您查看 g++ 的预处理器输出,它没有对代码重新排序或任何此类胡说八道,当然还有 iostream没有定义 operator!=对于 A .

我手边没有我的 C++ 标准拷贝,但是 this link IBM 至少证实了未命名命名空间与全局命名空间不能很好地混合的说法,解释了为什么你找不到 operator!=你已经定义了。

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

关于c++ - 未命名的命名空间和 iostream 导致 "!= being illegal operation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8488849/

相关文章:

android - 使用 Kotlin 函数特性如何使这段代码更好?

c++ - 在g++中收到的预期主表达式

GCC,-W1 是什么意思

c++ - 编译器在不需要时关心复制构造函数

c++ - 逗号运算符如何工作

c++ - 如何将 SWIG 与 "using"一起使用

haskell - 我们可以在 Hindley Milner 类型系统的构造函数位置有类型变量吗?

c++ - 如何让一个变量依赖于一个类中的其他变量?

typescript - 并行运行一组 TaskEithers,但如果 1 个或多个任务失败则继续

c++ - 无法在 MinGW 中捕获 bad_alloc