从函数模板类型中提取返回类型

Extracting return type from function template type

本文关键字:提取 返回类型 类型 函数模板      更新时间:2023-10-16

我有一个类似于以下内容的包装函数:

template<typename Func, typename ... Args>
void func(Func f, Args ... args) {
  ...
  f(args...);
  ...
}

是否可以在编译时从类型Func中提取返回类型?

例如,用户具有代码并按以下方式调用func

template<typename T>
T add(const T& l, const T& r) {
  return l + r;
}
int main(int argc, char** argv) {
  double a = 4.5, b = 5.5;
  func(add<double>, a, b);
  return 0;
}
我们可以在调用

func时推断出一个返回double的函数被传递给它吗?我想将返回类型信息用于func中的其他内容。

以下任一方法都可以

using result_type = decltype(std::declval<Func>()(std::declval<Args>()...));

using result_type = typename std::result_of<Func(Args...)>::type;

现场演示

由于 c++17 std::invoke_result

using result_type = typename std::invoke_result_t<Func(Args...)>;

如果你可以访问C++14,或者只是出于好奇,尽量不要提交到特定的类型。以下代码使用泛型 lambda,并为您推断类型。在许多情况下,我发现使用起来要容易得多。

#include <iostream>
using namespace std;
template<typename Func, typename ... Args>
void func(Func&& f, Args ... args) {
  return;
}
auto add = [](auto l, auto r) { return l * r; };
int main() 
{
    auto a = double{4.5};
    auto b = double{5.5};
    func(add, a, b);
    return 0;
}

Ideone:http://ideone.com/wXnc0g