本文介绍了为什么C ++参数范围影响命名空间中的函数查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎有点向后,但它的工作原理:

This seems a little backwards to me but it works:

 c>声明将标识符带入范围,否则您必须限定调用。

That is ADL (Argument Dependent Lookup) or Koenig Lookup (for the designer of the feature). The purpose of the feature is that in many cases the same namespace will contain types and functions that can be applied to those types, all of which conform the interface. If ADL was not in place, you would have to bring the identifiers into scope with using declarations or you would have to qualify the calls.

这成为一个噩梦,因为语言允许运算符重载。请考虑以下示例:

This becomes a nightmare since the language allows for operator overloads. Consider the following example:

namespace n {
   struct test {};
   test operator+( test, test const & ); // implemented
};
int main() {
   n::test a,b;
   n::test c = a + b;  //without ADL: c = n::operator+( a, b )
}

虽然它可能看起来像一个尴尬的情况,考虑 n 可能是 std 命名空间,测试可以是 ostream 和 operator 可以是 < :

While it might seem like an awkward situation, consider that n might be the std namespace, test might be ostream, and operator+ could be operator<<:

int main( int argc, char** ) {
   std::cout << "Hi there, there are " << argc << " arguments" << std::endl;
}

没有ADL时,调用 operator< 必须是显式的,此外,你必须知道哪些是实现为自由函数对方法。你知道 std :: cout<< Hi正在调用一个自由函数, std :: cout< 5 正在调用成员函数?没有多少人意识到,认真,几乎没有人关心。 ADL隐藏了你。

Without ADL, the calls to operator<< would have to be explicit, and moreover you would have to know which of them is implemented as a free function versus a method. Did you know that std::cout << "Hi" is calling a free function and std::cout << 5 is calling a member function? Not many people realize it, and seriously, almost no one cares. ADL hides that from you.

这篇关于为什么C ++参数范围影响命名空间中的函数查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:23