Getting the Return Type of a Templatized Object's Method

我的未来我决定 提交于 2019-12-10 08:37:23

问题


Say that I have:

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

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.

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?

EDIT: 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.


回答1:


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

 result_of<F(ArgTypes...)>

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, "!");

Or we could just use decltype:

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

which is much more natural.


Given bar, that's just:

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

as opposed to:

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


来源:https://stackoverflow.com/questions/32910315/getting-the-return-type-of-a-templatized-objects-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!