(23条消息) 尾置返回值类型decltype_最后冰吻free的博客-CSDN博客

PHOTO EMBED

Thu Nov 24 2022 06:07:05 GMT+0000 (Coordinated Universal Time)

Saved by @leawoliu

#include <iostream>
#include <type_traits> // std::decay


// 若返回值类型与参数类型有关,可以让编译器自动推导
template<typename T1, typename T2>
auto max(T1 t1, T2 t2) {
    return t1<t2?t2:t1;
}

// 等价上面,使用decay对类型进行弱化,去掉const、引用等
template<typename T1, typename T2>
auto max1(T1 t1, T2 t2)->typename std::decay<decltype(true?t2:t1)>::type {
    return t1<t2?t2:t1;
}

// 若T是引用时,使用尾置返回值类型可能被推导为引用类型
template<typename T1, typename T2>
auto max2(T1 t1, T2 t2)->decltype(true?t2:t1) {
    return t1<t2?t2:t1;
}



// common_type<>和decay也是返回值类型退化的
template<typename T1, typename T2>
std::common_type<T1, T2> max3(T1 t1, T2 t2) {
    return t1<t2?t2:t1;
}

void Test(){
    std::cout<<std::boolalpha<<std::is_same_v<decltype(max(4, 7.2)), double><<std::endl; // true
    std::cout<<std::boolalpha<<std::is_same_v<decltype(max(7.2, 4)), double><<std::endl; // true

    double a = 7.2;
    double &b = a;
    int c = 4;

    std::cout<<std::boolalpha<<std::is_reference_v<double&><<std::endl; //true
    std::cout<<std::boolalpha<<std::is_same_v<decltype(max2(b,c)), double><<std::endl; // true, 推导应该为double&才对啊
    std::cout<<std::boolalpha<<std::is_reference_v<decltype(max2(b,c))><<std::endl; // false, 为啥测试结果是double而不是double&

}


int main()
{
     Test();
}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
content_copyCOPY

https://blog.csdn.net/CodeHouse/article/details/126290602