从转发函数的类型推断出模板化返回类型

时间:2017-03-15 20:43:37

标签: c++ c++11 variadic-templates std-function perfect-forwarding

我正在尝试编写一个包含函数的头文件,该函数调用main.cpp中的函数,转发任意数量的参数。此代码的返回类型需要与转发函数的返回类型匹配。为了实现这一点,我编写了以下虚拟程序,但我无法编译。我会感激一些帮助:

#include <functional>
#include <iostream>

double f(double x, int params) {
    return 1;
}

template <typename func, typename... Args>
double test(std::function<func(double, Args...)> predicate, Args&&... params){
    return 2;
}

int main() {
    int dummy = 1;
    double result = test(&f, dummy);
    std::cout<<result<<std::endl;
    return 0;
}

编译器(clang ++ - 3.8)给出以下错误:

test.cpp:15:18: error: no matching function for call to 'test'
        double result = test(&f, dummy);
                    ^~~~
test.cpp:9:8: note: candidate template ignored: could not match
      'function<type-parameter-0-0 (double, type-parameter-0-1...)>'  against
      'double (*)(double, int)'
double test(std::function<func(double, Args...)> predicate, Args&&... params){
       ^
1 error generated.

1 个答案:

答案 0 :(得分:2)

这个怎么样:

#include <utility>

template <typename F, typename ...Args>
auto test(F&& f, Args&&... args)
    -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)) {
  return std::forward<F>(f)(std::forward<Args>(args)...);
}

用法:

test(f, j, dummy);

在C ++ 14中,您可以更简单地将其写为:

template <typename F, typename ...Args>
decltype(auto) test(F&& f, Args&&... args) {
  return std::forward<F>(f)(std::forward<Args>(args)...);
}