为什么大多数C++编译器能够推断出它的类型::isspace并将其隐式转换为std::function,但是他们无法做到这一点std::isspace?
请参阅以下不编译的内容:
#include <cctype>
#include <functional>
template <typename Functish>
bool bar1(Functish f) { return f('a'); }
inline bool bar2(std::function<bool(char)> f) { return f('a'); }
#if 1
#define ff &std::isspace
#else
#define ff &::isspace
#endif
#if 0
bool foo()
{
return bar1(ff);
}
#else
bool foo()
{
return bar2(ff);
}
#endif
Run Code Online (Sandbox Code Playgroud)
在Compiler Explorer支持的编译器中,ELLCC似乎是唯一std::isspace具有我期望的可推导性/可转换性的编译器.
有多个重载std::isspace,但只有一个::isspace.
头<cctype>声明了一个函数int std::isspace(int),它也可能在全局命名空间中声明了相同的函数(尽管如此).
头文件<locale>定义了一个函数模板template <class CharT> bool std::isspace(CharT, const std::locale&).
头文件<ctype.h>声明了一个函数int isspace(int),它也可以在命名空间中声明相同的函数std(尽管如此).
似乎在ELLCC之外的编译器中,<cctype>包括<locale>(或者两个std::isspace重载都在其他地方声明并包含在两个头中).标准仅指定标准头必须声明的符号; 它并不禁止他们声明其他不需要的符号.
由于std::isspace过载,您必须将其强制转换,int(*)(int)以便编译器知道要选择哪个重载.