简体   繁体   English

如何在 c++17 或 20 中使用 std::invoke_result_t 而不是 c++14 中的 std::result_of_t?

[英]How to use std::invoke_result_t in c++17 or 20 instead of std::result_of_t in c++14?

when I use std::result_of_t in c++14 it's doing as i wish:当我在 c++14 中使用 std::result_of_t 时,它按我的意愿做:

void just_simple()
{
    std::cout << "【4】: in func return nothing. " << std::endl;
}

template<typename Callback, typename... Args>
auto InTemplate_Call(Callback&& bc, Args&&... args)
{
    typedef typename std::result_of_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;

    //typedef typename std::invoke_result_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;

    if (typeid(ReturnType) == typeid(void))
    {
        std::cout << "get a void type" << std::endl;
    }

    return rtDeduction<ReturnType>::type();
}

int main(){
    InTemplate_Call(just_simple);

    return 0;
}

The ReturnType is just void . ReturnType只是void

But It's not work in c++17 or 20:但它在 c++17 或 20 中不起作用:

template<typename Callback, typename... Args>
auto InTemplate_Call(Callback&& bc, Args&&... args)
{
    //typedef typename std::result_of_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;

    typedef typename std::invoke_result_t<std::decay_t<Callback>(std::decay_t<Args>...)> ReturnType;

    if (typeid(ReturnType) == typeid(void))
    {
        std::cout << "get a void type" << std::endl;
    }

    return rtDeduction<ReturnType>::type();
}

The ReturnType is not void anymore! ReturnType不再是void了!

Is there anything I made mistake?有什么我做错了吗?

The difference between invoke_result and result_of is that the former accepts the callable type and arguments type, but your std::decay_t<Callback>(std::decay_t<Args>...) is just a function type that returns a std::decay_t<Callback> . invoke_resultresult_of的区别在于前者接受可调用类型和参数类型,但你的std::decay_t<Callback>(std::decay_t<Args>...)只是一个返回std::decay_t<Callback>函数类型std::decay_t<Callback>

The following shows the differences:以下显示了差异:

#include <functional>

void just_simple() {}

template<typename Callback>
void foo(Callback&&)
{
  static_assert(std::is_same_v<std::invoke_result_t<Callback()>, Callback>);
  static_assert(std::is_same_v<std::invoke_result_t<Callback  >, void>);
}

int main() {
  foo(just_simple);
}

You should do this:你应该做这个:

typedef typename std::invoke_result_t<
  std::decay_t<Callback>, 
  std::decay_t<Args>...> ReturnType;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM