获取模板化对象方法的返回类型 [英] Getting the Return Type of a Templatized Object's Method

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

问题描述

说我有:

template <typename T>
struct Foo {
    T& func();
};

我实现了一个 Foo: Foobar 现在我想获取 bar.func() 的返回类型.我一直在试图强制 result_of 工作和我在一起但无济于事.

And I implement a Foo: Foo<int> bar Now I want to get the return type of bar.func(). I've been trying to force result_of to work with me but to no avail.

我真正想要的是能够做 result_of_t<foo.func> 并完成它,但我想这要困难得多?我应该如何获取这种返回类型?

What I'd really like is to just be able to do result_of_t<foo.func> and be done with it but I imagine it's significantly more difficult? How should I go about getting this return type?

我希望在不考虑 bar 的声明方式的情况下实现这一点.也就是说,我只想能够将 bar.func 传递给 result_of 或类似的东西,然后输出返回类型.

I was hoping to accomplish this without without respect to how bar was declared. That is to say, I want to just be able to pass bar.func into result_of or similar and gt out the return type.

推荐答案

std::result_of 实际使用起来很烦人.它的语法是:

std::result_of is pretty annoying to use actually. Its syntax is:

 result_of<F(ArgTypes...)>

其中 F 是可调用的,这里的一切都是类型.在您的情况下,您想要调用一个成员函数:&Foo::func.但是您需要的不是成员指针的,而是类型.所以我们想要 decltype(&Foo.调用成员函数的方式是传递对象的实例作为第一个参数.

Where F is something invokable, and everything here is a type. In your case, you want to invoke a member function: &Foo<int>::func. But it's not the value of the pointer-to-member that you need, but the type. So we want decltype(&Foo<int>::func). The way to invoke a member function is to pass an instance of the object as the first argument.

把它们放在一起,我们得到:

Put it all together and we get:

using T = std::result_of_t<decltype(&Foo<int>::func)(Foo<int>&)>;
static_assert(std::is_same<T, int&>::value, "!");

或者我们可以使用 decltype:

using T = decltype(std::declval<Foo<int>&>().func());

这更自然.

给定 bar,就是:

using T = decltype(bar.func());

相反:

using T = std::result_of_t<decltype(&decltype(bar)::func)(decltype(bar))>;

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

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