令我惊讶的是,这段代码可以正确编译和执行。这是怎么回事?

For my surprise this code compiles and executes correctly. What's happening here?

本文关键字:编译 执行 怎么回事 代码 段代码      更新时间:2023-10-16

我从这里获得了下面的例子,副标题是"解决方案"。

对我来说,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);

根本没有+对您的对象进行操作。