首页 > 解决方案 > What is the type of decltype(*int_iterator + 0)?

问题描述

template <typename AIterator>
auto foo(AIterator begin) -> decltype(*begin + 0){
    return *begin;
}

For example:

vector<int> ivec = {1,2,3};
foo(ivec.begin());

My answer book says it's a const reference type, is it true?

But IIRC, decltype(int reference + int), expression type is a int (*begin is a reference, so naturally I think *begin + 0 should also result in a int).

For example:

int a = 3, &b = a;
decltype(b + 0) d; //d is a int

PS: I tried on VS and the IDE hints the return type of function foo is int.

The book is C++ Primer 5th answer book, but mine is not a English version and it's adapted by the translators, so I didn't mention it at first.

enter image description here

标签: c++

解决方案


它是int, 这正是作者添加+ 0... 作为摆脱引用类型并确保foo返回副本的快速方法的原因(这似乎是它的目的)。

decltype在类型的纯右值表达式上T 总是计算为T.

要么这本书的散文是错误的,要么你读错了。


推荐阅读