【问题标题】:How to obtain the return type of a function passed into a templated function or class?如何获取传递给模板化函数或类的函数的返回类型?
【发布时间】:2021-02-07 16:14:45
【问题描述】:

如何以这种方式获取函数的返回类型(传递给高阶函数/类):

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
}

【问题讨论】:

    标签: c++ c++11 templates template-classes


    【解决方案1】:

    确实,您可以像这样使用decltype

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

    这是demo

    【讨论】:

    • 我明白了。如果func() 接受的参数——比如说两个 T 类型的参数——应该如何扩展它来适应这个?
    • @SappyB。编辑了答案。
    猜你喜欢
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多