search

Home  >  Q&A  >  body text

C++中如何详细的使用尾置返回类型?

例如返回一个函数指针,如何使用下面的pf呢

auto pf(const string &, const string &) -> bool (*)(const string &s1, const string &s2);

bool LengthCompare(const string &temp1, const string &temp2)
{
    return temp1 < temp2;
}
伊谢尔伦伊谢尔伦2803 days ago508

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:10:35

    I think you must have made something wrong. First, in C++, the function pf accepts two strings and then returns a function pointer (important: it is not a closure). This new function accepts two more strings and returns bool. This kind of function is almost meaningless unless the purpose of the two strings is to find a function to return.

    Generally speaking, tailing return types is used to use decltype, or simply to make the code more readable. For example, the pf above has another way of writing:

    bool(*pf)(const string&, const string&)(const string&, const string&);
    

    An example of decltype is as follows. For example, you may not know what type a+b returns:

    template<typename T, typename U>
    auto Add(T t, U u) -> decltype(t + u)
    {
        return t + u;
    }
    

    In this way you can not only Add(1, 2), but also Add(3.0, 4.0f), and even Add("VczhIsAGenius", 7).

    Finally, if you say how to use such a PF, it must be similar to the following writing:

    bool result = pf("1", "2")("a", "b");
    

    I suggest you re-examine your question.

    reply
    0
  • Cancelreply