c++ primer中auto与decltype

看c++ primer,对auto和decltype有些疑问,搜索看到geekforgeeks上面的一篇文章中的例子:

// C++ program to demonstrate use of decltype in functions 
#include <bits/stdc++.h> 
using namespace std; 

// A generic function which finds minimum of two values 
// return type is type of variable which is minimum 
template <class A, class B> 
auto findMin(A a, B b) -> decltype(a < b ? a : b) 
{ 
    return (a < b) ? a : b; 
} 

// driver function to test various inference 
int main() 
{ 
    // This call returns 3.44 of doubale type 
    cout << findMin(4, 3.44) << endl; 

    // This call returns 3 of double type 
    cout << findMin(5.4, 3) << endl; 

    return 0; 
} 

这个例子中的return type,去掉->decltype(a<b?a:b)编译运行,结果与添加这个是一致的。这是为何,在哪种情况下,不加这段代码会有问题?

补充answer from fefe

// C++ program to demonstrate use of decltype in functions
#include <bits/stdc++.h>
using namespace std;

// A generic function which finds minimum of two values
// return type is type of variable which is minimum
template <class A, class B>
auto findMin(A a, B b)->decltype(a<b ? a:b)
{
    if(a > 4)
       return 1;
    else if(a >5)
       return 2.0;
    else
       return 3;
}

// driver function to test various inference
int main()
{
    // This call returns 3.44 of doubale type
    cout << findMin(4, 3.44) << endl;

    // This call returns 3 of double type
    cout << findMin(5.4, 3) << endl;

    return 0;
}

这种情况下,如果去掉decltype会报错。

维基百科中的一个例子:

int& foo(int& i);
float foo(float& f);

template <class T> auto transparent_forwarder(T& t) −> decltype(foo(t)) {
  return foo(t);
}

如果foo(t)返回的是个引用,此时用auto也会有问题。
auto需要手动添加&当处理引用时。

阅读 1.9k
1 个回答

使用 auto 作为返回类型,并且没有 trailing return type,实际的返回类型将由 return 语句进行推断。

有时候推断会失败,比如函数里同时含有 return 1;return 1.0; (int? double?)。这时没有 trailing return type 就会是一个错误。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题