gpt4 book ai didi

c++ - Koenig 的查找是否适用于此?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:24 24 4
gpt4 key购买 nike

以下片段是否正确的 C++ 代码?

#include <sstream>
class Foo;
std::ostream& operator<<(std::ostream& str, Foo x); // (A)

namespace test {
class Message {
public:
std::ostringstream str;
};

template<typename T>
Message& operator<<(Message& m, T& t)
{
using ::operator<<;
m.str << t;
return m;
}
}

namespace detail {
class Class {
public:
int i;
Class() : i(5) {}
};
}

std::ostream& operator<<(std::ostream& str, detail::Class& myClass) { // (B)
return str << myClass.i;
}

int main() {
test::Message m;
detail::Class c;
m << c;
}

根据 http://goo.gl/NkPNau GCC 编译得很好,而 Clang 没有找到 operator<< (B).


如果您想知道:这是来自将 GTest 与自定义 operator<< 结合使用的代码对于 std::set打印漂亮的断言消息。除了将 operator<< (B) 在 std 命名空间中(是的,我知道...)。

最佳答案

Clang 在这里是正确的。让我们将 g++ 的行为称为语言扩展。

参数相关查找(又名 Koenig 查找)确实适用,因为 m.str << t使用匹配 m.str.operator<<(t) 的最佳重载进行解释或 operator<<(m.str, t) , 第二种情况是 unqualified-id 作为函数名。但是:

14.6.4.2:

For a function call that depends on a template parameter, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2, 3.4.3) except that:

  • For the part of the lookup using unqualified name lookup (3.4.1) or qualified name lookup (3.4.3), only function declarations from the template definition context are found.

  • For the part of the lookup using associated namespaces (3.4.2), only function declarations found in either the template definition context or the template instantiation context are found.

If the function name is an unqualified-id and the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in all translation units, not just considering those declarations found in the template definition and template instantiation contexts, then the program has undefined behavior.

在模板定义上下文中,(B) 不可见。 (B) 在模板实例化上下文中可见,但全局命名空间不是 std::ostringstream 的关联命名空间或 detail::Class .

关于c++ - Koenig 的查找是否适用于此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25295345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com