C++ 模板方法未知 return 类型

C++ Template method unknown return type

我把运行改成一段代码我就不跟了。考虑以下两种方法。

template <typename T>
auto FindElementV1(std::vector<T> elementList, const T& element) {
 return std::find(elementList.begin(), elementList.end(), element);     
}

template <typename T>
auto FindElementV2(std::vector<T> elementList, const T& element) -> typename decltype(elementList)::iterator {
 return std::find(elementList.begin(), elementList.end(), element);     
}

我可以理解 FindElementV2 工作,因为该方法的 return 类型是使用 decltype 指定的。但是为什么 FindElementV1 在没有指定 return 类型的情况下工作? V1 是一段符合标准的代码吗?

下面是完整的工作示例。符合 gcc 6.3

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

template <typename T>
auto FindElementV1(std::vector<T> elementList, const T& element) {
 return std::find(elementList.begin(), elementList.end(), element);     
}

int main() {
    std::vector<int> vec = {1,4,2,4,3,5,3,5,3,6};
    auto it = FindElementV1(vec, 5); //< Why does this work without a return type in the method?
    cout<<*it<<endl;
}

[dcl.spec.auto]

If the declared return type of the function contains a placeholder type, the return type of the function is deduced from non-discarded return statements, if any, in the body of the function

还有

If a function with a declared return type that contains a placeholder type has multiple non-discarded return statements, the return type is deduced for each such return statement. If the type deduced is not the same in each deduction, the program is ill-formed.

丢弃的语句是出现在 constexpr if 语句 [stmt.if] 的非采用分支中的语句.

C++14 使我们能够编写推导出 return 类型的函数:

auto foo() { return 5; }

在 C++11 中,这是格式错误的 - 您需要以某种方式指定 return 类型。在 C++14 中,我们可以从 return 语句中保守地推断出 return 类型。保守地说,我的意思是如果有多个——它们都需要是同一类型,如果你递归,你需要递归第二个而不是第一个。

扣除遵循正常的模板扣除规则。所以这个:

auto foo(int& i) { return i; }

return 是 int,而不是 int&

所有这一切都是说,是的,FindElementV1 是一个完全有效的函数模板……从 C++14 开始。