Jon*_*Mee 4 c++ templates return-type result-of template-meta-programming
说我有:
template <typename T>
struct Foo {
T& func();
};
Run Code Online (Sandbox Code Playgroud)
我实现了一个Foo:Foo<int> bar现在我想获得返回类型bar.func().我一直试图强迫result_of与我合作,但无济于事.
我真正喜欢的是能够做到result_of_t<foo.func>并完成它但我想它会更加困难吗?如何获得这种返回类型?
编辑:
我希望在没有尊重bar声明的情况下完成此任务.也就是说,我想就能够通过bar.func进入result_of或相似和GT出来的返回类型.
std::result_of真的很烦人.它的语法是:
result_of<F(ArgTypes...)>
Run Code Online (Sandbox Code Playgroud)
哪里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, "!");
Run Code Online (Sandbox Code Playgroud)
或者我们可以使用decltype:
using T = decltype(std::declval<Foo<int>&>().func());
Run Code Online (Sandbox Code Playgroud)
这更自然.
鉴于bar,这只是:
using T = decltype(bar.func());
Run Code Online (Sandbox Code Playgroud)
而不是:
using T = std::result_of_t<decltype(&decltype(bar)::func)(decltype(bar))>;
Run Code Online (Sandbox Code Playgroud)