Questions tagged «return-type-deduction»

2
decltype(auto)有什么用?
Наэтотвопросестьответына 堆栈溢出нарусском:Конструкцияdecltype(自动) 在c ++ 14中,decltype(auto)引入了惯用语。 通常,它的用途是允许auto声明使用decltype给定表达式上的规则。 在搜索“良好”使用该用法的示例时,我只能想到以下内容(由Scott Meyers撰写),即函数的返回类型推导: template<typename ContainerType, typename IndexType> // C++14 decltype(auto) grab(ContainerType&& container, IndexType&& index) { authenticateUser(); return std::forward<ContainerType>(container)[std::forward<IndexType>(index)]; } 还有其他使用此新语言功能的示例吗?

7
什么时候应该使用C ++ 14自动返回类型推导?
随着GCC 4.8.0的发布,我们有了一个支持自动返回类型推导的编译器,它是C ++ 14的一部分。使用-std=c++1y,我可以这样做: auto foo() { //deduced to be int return 5; } 我的问题是:什么时候应该使用此功能?什么时候需要,什么时候可以使代码更简洁? 场景1 我能想到的第一种情况是尽可能的。可以用这种方式编写的每个函数都应该如此。这样做的问题是,它可能并不总是使代码更具可读性。 方案2 下一种情况是避免使用更复杂的返回类型。作为一个非常简单的示例: template<typename T, typename U> auto add(T t, U u) { //almost deduced as decltype(t + u): decltype(auto) would return t + u; } 尽管在某些情况下让返回类型显式依赖于参数,但我认为这绝对不会成为问题。 场景3 接下来,为了防止冗余: auto foo() { std::vector<std::map<std::pair<int, double>, …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.