Ben*_*igt 6 c++ overloading header backwards-compatibility cmath
即将推出的C++ 0x标准的最终委员会草案说:
每个C头(每个头都具有name.h形式的名称)的行为就好像每个由相应的cname头放置在标准库命名空间中的名称放在全局命名空间范围内.未指定是在名称空间std的名称空间作用域(3.3.6)中首先声明或定义这些名称,然后通过显式使用声明(7.3.3)将这些名称注入到全局名称空间作用域中.
早期的C++标准读起来类似.
我的问题是,当C++标头#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;
}
Run Code Online (Sandbox Code Playgroud)
编译就绪测试用例:
math.h和stdlib.h:http://ideone.com/pmD4tmath.h和stdlib.h:http://ideone.com/Sflpncmath和cstdlib:http://ideone.com/yI07mcmath仅限C++ :http://ideone.com/KrS3W从这个测试来看,C++ math.h就像C一样,而不像C++ cmath.
但在Visual C++ 2010上,C++ math.h就像C++一样cmath.
和Comeau试用的编译时金丝雀:
#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;
}
Run Code Online (Sandbox Code Playgroud)
结果:
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".
Run Code Online (Sandbox Code Playgroud)
Comeau同意Visual C++.
是的,所有重载都应该放入全局命名空间中。我的理解是math.h标题看起来像这样:
// math.h:
#include <cmath>
using std::abs;
// etc.
Run Code Online (Sandbox Code Playgroud)
所以,是的:示例程序编译为 C 程序时的行为与编译为 C++ 程序时的行为不同。作为 C++ 程序,它将std::abs(double)从<math.h>. 作为 C 程序,它将调用abs(int)(<stdlib.h>这是 C 标准库中的唯一abs函数,因为 C 不支持函数重载)。
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |