为什么大多数 C++ 编译器能够推导出 ::isspace
的类型并将其隐式转换为 std::function
,但他们不能为 std::isspace
这样做?
请参阅无法编译的 the following:
#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
在 Compiler Explorer 支持的编译器中,ELLCC 似乎是唯一一个
std::isspace
具有我期望的可推论/可转换性的编译器。 最佳答案
std::isspace
有多个重载,但只有一个 ::isspace
。
header 声明了一个函数 int std::isspace(int)
,它也可能在全局命名空间中声明了相同的函数(虽然它不是必须的)。
头文件 定义了一个函数模板 template <class CharT> bool std::isspace(CharT, const std::locale&)
。
头文件 声明了一个函数 int isspace(int)
,它也可以在命名空间 std
中声明相同的函数(虽然它不是必须的)。
似乎在 ELLCC 之外的编译器上, 包括 (或者两个 std::isspace
重载都在其他地方声明并包含在两个 header 中)。该标准只规定了标准头文件必须声明哪些符号;它并不禁止他们声明其他不需要的符号。
由于 std::isspace
已重载,因此您必须将其强制转换为 int(*)(int)
,以便编译器知道要选择哪个重载。
关于c++ - 在 C++ 中,为什么 <cctype> 定义了 std::isspace 和::isspace?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46208733/