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

时间:2015-10-02 15:09:54

标签: c++ templates template-meta-programming return-type result-of

说我有:

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

我实施了FooFoo<int> bar现在我想获得bar.func()的返回类型。我一直试图强迫result_of与我合作,但无济于事。

我真正喜欢的是能够完成result_of_t<foo.func>并完成它但我想它会更加困难吗?我应该如何获得这种返回类型?

修改 我希望在不尊重bar声明的情况下完成此任务。也就是说,我希望能够将bar.func传递给result_of或类似的传递,并输出返回类型。

1 个答案:

答案 0 :(得分:6)

实际使用

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