c++ - 函数模板 : why ambiguity is generated?

标签 c++ templates

我有以下简单的函数模板:

最大马力:

template <typename T>
inline T const& max (T const& a, T const& b)
{
   return a <b? b :a;
}

最大.cpp

#include <iostream>
#include <string>
#include "max.hpp"

int main()
{
  int i = 42;
  std::cout << "max(7,i): " << ::max(7,i) << std::endl;

  double f1 = 3.4;
  double f2 = -6.7;
  std::cout << "max(f1,f2): "<< ::max(f1,f2) << std::endl;

  std::string s1 = "mathematics";
  std::string s2 = "math";
  std::cout << "max(s1,s2): " << ::max(s1,s2) << std::endl;
  std::cin.get();
  return 0;
}

这很好用,因为 ::将告诉编译器搜索 max全局命名空间中的模板。但是,当我删除那些 ::在这 3 种情况下,我收到以下歧义错误消息:

max.cpp: In function ‘int main()’:
max.cpp:21:43: error: call of overloaded ‘max(std::string&, std::string&)’ is ambiguous                                            
max.hpp:2:17: note: candidates are: const T& max(const T&, const T&) 
 [with T = std::basic_string<char>]                                          
/usr/lib/gcc/i686-pc-cygwin/4.5.3/include/c++/bits/stl_algobase.h:209:5: 
note: const  _Tp& std::max(const _Tp&, const _Tp&) 
[with _Tp = std::basic_string<char>]   

我的问题如下:

  1. 在这种情况下,编译器是否搜索 std默认命名空间即使我没有包含头文件<algorithm>其中 std::max位于?

  2. global namespace 中放置了什么? ?是否需要使用 ::global namespace 中调用函数时在所有情况下?

  3. 为什么max时没有歧义适用于 integerfloat类型,只有 string 有歧义类型?

仅供引用:我正在使用 gcc 4.5.3 进行编译。 谢谢!

最佳答案

In this case, does the compiler search for std namespace by default even I did not include the header file where std::max is located?

是的,这叫做Argument Dependent Lookup .请注意,定义 std::max 的头文件可能包含在您包含的某些文件中。

What are placed in the global namespace? Is it required to use the :: when calling functions in global namespace under all circumstances?

不,只有在有歧义的时候。这是其中一个案例。

Why there is no ambiguity when max is applied on integer and float type, only has ambiguity for string type?

因为 intfloat 都没有在命名空间 std 中定义。因此,编译器不会查看该命名空间内部,因此 std::max 在重载解析期间不被考虑。 std::string 不是这种情况。

请注意,如果这样做,您可能会引发同样的歧义:

using namespace std;

或者:

using std::max;

关于c++ - 函数模板 : why ambiguity is generated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725626/

相关文章:

c++ - 如何分析哪部分代码创建了线程?

c++ - C++ 中的函数指针转换

c++ - 模板构造函数中的模板类特化

c++ - 我不明白这个 C++ 模板是如何工作的

c++ - C++ 中的析构函数

c++ - 警告信息的目的?

c++ - 移动 Boost asio TCP 流

templates - 模板中变量的默认值

c++ - 如何将不同的模板类型放入一个 vector 中

c++ - ‘<’ 标记之前预期的构造函数、析构函数或类型转换