invoke_result获取模板成员函数的返回类型 [英] invoke_result to obtain return type of template member function

查看:686
本文介绍了invoke_result获取模板成员函数的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取模板成员函数的结果类型?

How can I obtain the result type of a template member function?

下面的最小示例说明了这个问题.

The following minimal example illustrates the problem.

#include <type_traits>

template <typename U>
struct A {
};

struct B {
   template <typename F = int>
   A<F> f() { return A<F>{}; }

   using default_return_type = std::invoke_result_t<decltype(f)>;
};

int main()
{
    B::default_return_type x{};

    return 0;
}

在Coliru上观看实时.

See it live on Coliru.

代码无法编译,出现错误:

The code does not compile, giving error:

main.cpp:11:63:错误:decltype无法解析重载的地址 功能

main.cpp:11:63: error: decltype cannot resolve address of overloaded function

11 |使用default_return_type = std :: invoke_result_t;

11 | using default_return_type = std::invoke_result_t;

在模板参数F设置为默认值的情况下,获取B::f类型的正确语法是什么?

What is the correct syntax to obtain the type of B::f with the template parameter F set to default?

推荐答案

您可以获得以下返回类型:

You can get the return type like this:

using default_return_type = decltype(std::declval<B>().f());

完整示例:

#include <type_traits>
#include <iostream>
template <typename U>
struct A {
};

struct B {
   template <typename F = int>
   A<F> f() { return A<F>{}; }

   using default_return_type = decltype(std::declval<B>().f());
};

int main()
{
    B::default_return_type x{};
    std::cout << std::is_same< B::default_return_type, A<int>>::value;
}

PS:似乎clang和较旧的gcc版本对B是不完整的类型并调用f感到不满意.解决方法是,将using移出类应该有帮助.

PS: It seems like clang and older gcc versions are not happy with B being an incomplete type and calling f. As a workaround, moving the using out of the class should help.

这篇关于invoke_result获取模板成员函数的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆