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

时间:2013-07-07 17:59:47

标签: c++ templates

我在副标题"解决方案"

下从here获得了以下示例。

对我来说,对std::accumulate(a, a + 10, 0);main()的调用std::accumulate()中第二个参数的评估必须先于operator+(N::C, int)函数调用。也就是说,必须在函数N之前调用名称空间std::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); } 。但不仅此运算符定义,而且代码编译并正常执行。这里发生了什么?

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 = inta + 10。我对模板了解不多,但编译器如何推断出N::C也是{{1}}?

1 个答案:

答案 0 :(得分:6)

a + 10不会调用您班级的任何操作员。它只是将10添加到a,它是一个数组,在此上下文中衰变为指向其第一个元素的指针。您的代码相当于:

std::accumulate(&a[0], &a[10], 0);

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

相关问题