我从 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
不会调用您类(class)的任何运算符。它只是将 10
添加到 a
,它是一个数组,在此上下文中衰减为指向其第一个元素的指针。您的代码相当于:
std::accumulate(&a[0], &a[10], 0);
根本没有 +
可以对您的对象进行操作。
关于c++ - 令我惊讶的是,这段代码可以正确编译和执行。这里发生了什么事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17514734/