Home Item 13 - 返回類型推斷(return type deduction) (中文)
Post
Cancel

Item 13 - 返回類型推斷(return type deduction) (中文)

返回類型推斷(return type deduction)

發展到 C++14 後,覺得 C++ 語言開始變聰明了,也開始 care 它的 user(You, programmer) 了。哈 它可以幫你推斷的時候,且沒有模稜兩可的情況時,它竟量幫你做到!

直接看 code

function 可以這樣寫,return 直接寫 auto.

1
2
3
4
5
6
7
8
auto add(int a, int b) {
    return a + b;
}

auto multiply(double a, double b) {
    return a * b;
}

template 也可以這樣寫,return 直接寫 auto.

1
2
3
4
5
6
7
8
template<typename T>
auto sum(const std::vector<T>& vec) {
    T result = T();
    for (const auto& elem : vec) {
        result += elem;
    }
    return result;
}

最大好處就是 簡化函數定義:當函數的返回類型複雜或明顯時,使用返回類型推斷可以使代碼更簡潔。 我們可以更懶,哈!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍

Item 13 - Return type deduction (English)

Item 5 - Lambda expression (English)