How to deduce the type of the functor's return value?

前端 未结 1 1471
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 10:24

I would like to write a template function which accepts 2 values and a functor or a lambda. The function calls the functor with those values and returns the result.

1条回答
  •  有刺的猬
    2020-12-09 11:07

    You're nearly there; just use decltype:

    template  
    auto Apply(T x, T y, Fn fn) -> decltype(fn(x, y))
    {
      return fn(x, y);
    }
    

    You could use std::result_of (Difference between std::result_of and decltype) but why bother?

    template  
    typename std::result_of::type Apply(T x, T y, Fn fn)
    {
      return fn(x, y);
    }
    

    Regarding the follow-up question: for a function

    auto fn() ->  { return ; }
    

    substituting return-type with decltype() will usually work, but can be error prone. For example, consider:

    auto f(char c) -> decltype(std::string() += c) { return std::string() += c; }
    

    Here decltype will yield std::string & and your function will return an lvalue reference to a local! This would have to be changed to:

    auto f(char c) -> std::remove_reference::type {
        return std::string() += c;
    }
    

    In other cases, could yield a value that is not returnable for reason of being e.g. noncopyable, containing a lambda, etc.

    0 讨论(0)
提交回复
热议问题