在全局命名空间中默认包含equal()吗?

Wil*_*man 1 c++

这是关于C++中的默认全局命名空间的问题.我有以下代码使用g ++ clang-500.2.79编译和运行.

#include <string>
#include <iostream>

using std::string;
using std::endl; 
using std::cout;

bool is_palindrome(const string& str){
    return equal(str.begin(), str.end(), str.rbegin());
}

int main(){

    cout << "Hello is a palindrome: " << is_palindrome("Hello") << endl;
    cout << "madam is a palindrome: " << is_palindrome("madam") << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么这段代码编译正确?我忘了#include <algorithm>,并using std::equal在我的文件的开头.所以预期的行为是编译器抱怨.

http://en.cppreference.com/w/cpp/algorithm/equal上的示例确认我应该使用std::equal.

为了进一步研究这个问题,我试图确切地追踪equal()调用哪个版本的函数.作为C++的相对新手我也不知道如何做到这一点.我试过了,

cout << "The function is: " << equal << endl;
Run Code Online (Sandbox Code Playgroud)

这产生了编译器错误以及一些有趣的信息:

/usr/include/c++/4.2.1/bits/stl_algobase.h:771:5: 
note: 'std::equal' declared here
Run Code Online (Sandbox Code Playgroud)

尽我所能,我找不到有关stl_algobase的信息(或者更可能的是,我很可能不明白我发现了什么).是stl_algobase一组自动包含在全局命名空间中的函数吗?

另外一个问题是:当您在C++中处理潜在的重载或模板函数时,跟踪(代码或其他)函数的正确方法是什么?

jua*_*nza 5

equalstd命名空间中.你所看到的是参数依赖查找(ADL).因为参数位于std,所以名称查找equal也会考虑该命名空间.

这是一个简化的例子:

namespace foo
{
  struct Bar {};
}

namespace foo
{
  void bar(const Bar&) {}
  void bar(int) {}
}

int main()
{
  foo::Bar b;
  foo::bar(b);  // OK
  bar(b);       // ADL, OK
  foo::bar(42); // OK
  bar(42);      // No ADL: error: 'bar' was not declared in this scope
}
Run Code Online (Sandbox Code Playgroud)