获取模板化对象方法的返回类型

Getting the Return Type of a Templatized Object's Method

本文关键字:方法 返回类型 对象 获取      更新时间:2023-10-16

说我有:

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

我实现了一个Foo: Foo<int> bar现在我想得到bar.func()的返回类型。我一直试图强迫result_of和我一起工作,但无济于事。

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

编辑:

我希望在不考虑bar如何申报的情况下实现这一目标。也就是说,我只想将bar.func传递给result_of或类似的值,并输出返回类型。

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

 result_of<F(ArgTypes...)>

其中F是可调用的东西,这里的所有东西都是类型。在您的示例中,您希望调用一个成员函数:&Foo<int>::func。但是,您需要的不是指向成员的指针的,而是类型。我们想要decltype(&Foo<int>::func)。调用成员函数的方法是传递对象的实例作为第一个参数。

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

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))>;