令我惊讶的是,这段代码可以正确编译和执行.这里发生了什么事?

Bel*_*loc 1 c++ templates

我从获得下面的例子在这里的副标题"解决方案"下.

对我来说,调用std::accumulate(a, a + 10, 0);中的第二个参数的评估main()必须在std::accumulate()函数调用之前.也就是说,必须在函数之前调用operator+(N::C, int)in命名空间.但是不仅没有定义此运算符,而且代码编译和正常执行.这里发生了什么事?Nstd::accumulate()

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);
}
Run Code Online (Sandbox Code Playgroud)

而是调用此模板函数

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));
    }
Run Code Online (Sandbox Code Playgroud)

在哪里_InIt = N::C和_Ty = int.我对模板了解不多,但编译器如何推断出这a + 10也是一个N::C?

Car*_*rum 6

a + 10不会打电话给你班级的任何操作员.它只是增加10到a,其中,作为一个阵列,衰变成一个指向它的第一个元素在此上下文中.您的代码相当于:

std::accumulate(&a[0], &a[10], 0);
Run Code Online (Sandbox Code Playgroud)

不要+对你的物体进行操作.