What is the meaning of auto when using C++ trailing return type?

后端 未结 2 1544
走了就别回头了
走了就别回头了 2020-12-03 11:16

Instead of usual

void foo (void ) {
    cout << \"Meaning of life: \" << 42 << endl;
}

C++11 allows is an al

2条回答
  •  無奈伤痛
    2020-12-03 11:52

    Consider the code:

    template
    Tx Add(T1 t1, T2 t2)
    {
        return t1+t2;
    }
    

    Here the return type depends on expression t1+t2, which in turn depends on how Add is called. If you call it as:

    Add(1, 1.4);
    

    T1 would be int, and T2 would be double. The resulting type is now double (int+double). And hence Tx should (must) be specified using auto and ->

     template
        auto Add(T1 t1, T2 t2) -> decltype(t1+t2)
        {
            return t1+t2;
        }
    

    You can read about it in my article.

提交回复
热议问题