为什么 VC++ 编译代码而 clang 不编译?

Why does VC++ compile the code while clang doesn't?

本文关键字:编译 clang 代码 VC++ 为什么      更新时间:2023-10-16

我使用VS 2015 (Update 3)编译以下代码:

#include <codecvt>
#include <cctype>
#include <functional>
int main()
{
    std::function<int(int)> fn = std::isspace;
}

如果我用vc++编译它,它是可以的。但是,如果我在Visual Studio中将编译器更改为Visual Studio 2015 - Clang with Microsoft CodeGen (v140_clang_c2), clang报告一个错误:

main.cpp(7,26): error: no viable conversion from 'std::function'

std::function fn = std::isspace;

更令人惊讶的是,如果我像下面这样注释第一行,clang也可以。

//#include <codecvt> // now clang feels happy
#include <cctype>
#include <functional>
int main()
{
    std::function<int(int)> fn = std::isspace;
}

根本原因是什么?

std::isspace在标准库中被重载。

由于标准库头文件的结构不同,一个编译器会看到两个不同的名称声明。

那么不带参数或强制转换使用它是有歧义的。

std::isspace是不明确的,它既可以指<cctype>中为与C兼容而找到的函数,也可以指<locale>中找到的函数模板。

可以用

解决歧义
std::function<int(int)> fn = static_cast<int(*)(int)>(std::isspace);

或者省略std::命名空间,尽管技术上没有要求实现将C函数导入全局命名空间。

<codecvt>的Clang和GCC实现似乎都包含了<locale>的模板声明,因此出现了错误;