令我惊讶的是,这段代码可以正确编译和执行。这是怎么回事?
For my surprise this code compiles and executes correctly. What's happening here?
我从这里获得了下面的例子,副标题是"解决方案"。
对我来说,main()
年调用std::accumulate(a, a + 10, 0);
中第二个参数的评估必须在std::accumulate()
函数调用之前进行。也就是说,必须在函数std::accumulate()
之前调用命名空间N
中的operator+(N::C, int)
。但不仅没有定义这个运算符,而且代码可以正常编译和执行。这是怎么回事?
namespace N
{
class C {};
int operator+(int i, N::C) { return i+1; }
}
#include <numeric>
int main()
{
N::C a[10];
std::accumulate(a, a + 10, 0);
}
而是调用此模板函数
template<class _InIt,
class _Ty> inline
_Ty accumulate(_InIt _First, _InIt _Last, _Ty _Val)
{ // return sum of _Val and all in [_First, _Last)
_DEBUG_RANGE(_First, _Last);
return (_Accumulate(_Unchecked(_First), _Unchecked(_Last), _Val));
}
_InIt = N::C
和_Ty = int
的地方.我对模板了解不多,但是编译器如何推断a + 10
也是N::C
?
a + 10
不会调用类的任何运算符。 它只是向a
增加了10
,作为一个数组,在这种情况下衰减成指向其第一个元素的指针。 您的代码等效于:
std::accumulate(&a[0], &a[10], 0);
根本没有+
对您的对象进行操作。
相关文章:
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 在Linux上使用Clang / OLLVM交叉编译helloworld Windows可执行文件时的问题
- 尝试在Windows上执行C++时出错(通过MinGW编译)
- 编译的C可执行文件被Windows defender检测为病毒
- 编译的代码不执行文件写入
- 在C++中执行 N 阶乘编译时间的 3 种不同/相同方法
- C++项目编译强制使用 /clr 选项,尽管在没有公共语言运行时支持的情况下执行它
- 编译器如何在编译时执行数据绑定?
- Qt Creator 在执行步骤 "make" 时出现编译错误,-fno-stack-limit
- CPP 中 z3 的编译和执行命令?
- CMake 添加和删除宏定义以编译共享库/可执行文件
- 编译可执行文件之前未生成的文件
- 编译并执行C#程序中的C++代码
- 使用共享库编译可执行文件时仅链接所需的符号
- 在C++中编译/执行 GDAL 时出现问题
- c++11用户定义的字面量,与编译/执行二分法冲突
- 在Emacs中保存-编译-执行c++程序的快捷方式
- Raspi 的交叉编译 - 执行程序以 "Segmentation fault" 结束