我有以下简单的函数模板:
最大马力:
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>]
我的问题如下:
在这种情况下,编译器是否搜索
std
默认命名空间即使我没有包含头文件<algorithm>
其中std::max
位于?global namespace
中放置了什么? ?是否需要使用::
在global namespace
中调用函数时在所有情况下?为什么
max
时没有歧义适用于integer
和float
类型,只有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?
因为 int
和 float
都没有在命名空间 std
中定义。因此,编译器不会查看该命名空间内部,因此 std::max
在重载解析期间不被考虑。 std::string
不是这种情况。
请注意,如果这样做,您可能会引发同样的歧义:
using namespace std;
或者:
using std::max;
关于c++ - 函数模板 : why ambiguity is generated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725626/