如何获取传递到模板化函数或类中的函数的返回类型



如何以这种方式获得函数的返回类型(传递到高阶函数/类中(:

template <typename F>
auto DoSomething(F&& func) -> /* whatever type func returns */
{
// whatever...
return /* something that is func's type */
}

编辑:特别是如果func需要类型为T.的参数

我的直觉是decltypedeclval应该出现在画面中,但到目前为止,我还没有幸运地修改它。

更全面的上下文

struct Poop
{
float x;
int y;
}
Poop Digest(float a)
{
Poop myPoop{ a, 42 };
return myPoop;
}
template <typename F, typename T>
auto DoSomething(F&& func, T number) -> /* should be of type Poop  */
{
// whatever... Digest(number)... whatever...
return /* a Poop object */
}
int main()
{
Poop smellyThing;
smellyThing = DoSomething(Digest, 3.4f); // will work
}

实际上,您可以像这样使用decltype

template <typename F, typename T>
auto DoSomething(F&& func, T number) -> decltype(func(number))
{
// ...
return {};
} 

这是一个演示。

最新更新