c++ - 当 C++ 标准提供将名称带入全局命名空间的 C header 时,这是否包括重载?

标签 c++ header backwards-compatibility overloading cmath

即将发布的 C++0x 标准的最终委员会草案说:

Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).

早期的 C++ 标准读起来类似。

我的问题是,当 C++ header #include<cname>使用重载函数,都是#include<name.h>带来的重载,因为重载不是单独的“名称”?

以下代码的行为是否应该在符合标准的 C 和 C++ 编译器之间有所不同?

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
    double arg = -2.5;
    double result = abs(arg) / 3;
    printf("%f\n", result);
    return 0;
}

编译就绪的测试用例:

从这个测试中,C++ math.h行为像 C 而不像 C++ cmath .

但是在 Visual C++ 2010 上,C++ math.h行为像 C++ cmath .

还有一个用于 Comeau try-it-out 的编译时金丝雀:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

template<typename T> struct typecheck {};
template<> struct typecheck<int> { enum { value = 1 }; };

template<typename T>
typecheck<T> f(const T& t) { return typecheck<T>(); }

int main(void)
{
    double arg = -2.5;
    auto result = abs(arg) / 3;
    printf("%d\n", f(result).value);
    return 0;
}

结果:

Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing.  All rights reserved.
MODE:strict errors C++ C++0x_extensions

"ComeauTest.c", line 15: error: class "typecheck<double>" has no member "value"
      printf("%d\n", f(result).value);
                               ^

1 error detected in the compilation of "ComeauTest.c".

Comeau 同意 Visual C++。

最佳答案

是的,所有的重载都应该被带入全局命名空间。我的理解是 math.h标题旨在看起来像:

// math.h:
#include <cmath>

using std::abs;
// etc.

所以,是的:您的示例程序在编译为 C 程序时与编译为 C++ 程序时的行为不同。作为 C++ 程序,它将调用 std::abs(double)来自 <math.h> .作为 C 程序,它将调用 abs(int)来自 <stdlib.h> (这是 C 标准库中唯一的 abs 函数,因为 C 不支持函数重载)。

关于c++ - 当 C++ 标准提供将名称带入全局命名空间的 C header 时,这是否包括重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4405887/

相关文章:

C++ 使用 Bind 创建线程的问题

c++ - 代码arp数组、指针和内存分配的不可理解部分(Windows IP函数)

c++ 11 命令行参数分离

c++ - 包含在头文件中

c++ - 友元函数应该写在哪里?

ios - 检测 BOOL 可用性以支持多个 iOS 版本?

c++ - cv::Mat,在不知道矩阵类型的情况下在行列获取值

Apache CXF - 设置 HTTP header

javascript - EcmaScript-6 向后兼容性

java - JDK "upward"或 "backward"是否兼容?