c++ - 模板函数中的 std::function

标签 c++ templates c++11 stl

我试图编写一个模板函数,它可以接受仿函数作为参数并在之后调用它。程序如下:

#include <iostream>
#include <functional>
using namespace std;

template<typename R, typename... Args>
R call(function<R(Args...)> fun, Args... args)
{
    cout << "call@ " << __LINE__ <<endl;
    return fun(args...);
}

int main()
{
    cout << call(std::plus<int>(),1,2) <<endl;
    return 0;
}

G++ 提示:

g++ -c -Wall -std=c++0x -I../include a.cpp -o a.o
a.cpp: In function ‘int main()’:
a.cpp:16:38: error: no matching function for call to ‘call(std::plus<int>, int, int)’
a.cpp:16:38: note: candidate is:
a.cpp:7:3: note: template<class R, class ... Args> R call(std::function<_Res(_ArgTypes ...)>, Args ...)
a.cpp:7:3: note:   template argument deduction/substitution failed:
a.cpp:16:38: note:   ‘std::plus<int>’ is not derived from ‘std::function<_Res(_ArgTypes ...)>’
make: *** [a.o] Error 1

我想 std::plus<int>()可以推断为 std::function<int(int,int)> ,但它没有。那是为什么? GCC 是 gcc version 4.7.2 20120921 (Red Hat 4.7.2-2) (GCC)

最佳答案

I suppose std::plus() could be deduced to std::function

没有。鉴于您传递了 std::plus<int> 类型的对象,因此无法推断出.

在您的情况下,您不需要使用 std::function ,通常您会在存储可以使用特定签名调用的不同函数/函数对象时使用它。

这样,您就可以拥有自己的 call function 直接接受函数/函数对象,推导其原始类型,而不使用 std::function .此外,您可能还想在接受参数时使用完美转发并使用 std::forward将它们作为参数传递给函数/函数对象时。您还应该使用函数的返回类型作为 call 的返回类型.使用 C++11 的尾随返回类型 decltype为此。

#include <iostream>
#include <functional>
using namespace std;

template<typename R, typename... Args>
auto call(R fun, Args&&... args) -> decltype(fun(std::forward<Args>(args)...))
{
    cout << "call@ " << __LINE__ <<endl;
    return fun(std::forward<Args>(args)...);
}

int main()
{
    cout << call(std::plus<int>(),1,2) <<endl;
    return 0;
}

LIVE CODE


正如@Jan Hudec 所拥有的commented , __LINE__在所有对 call 的调用中,结果总是相同的, 无论传递什么函数。

关于c++ - 模板函数中的 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18606427/

相关文章:

c++ - 基础/派生模板类类型

C++11 并行化 : bottleneck in Armadillo's set_seed_random()

c++ - 为什么我不能将 unique_ptr 推回 vector 中?

c++ - 引用类构造函数定义私有(private)函数

c++ - 如何将文件从一个文件夹复制到另一个文件夹

c++ - 操作系统和编译器如何通信以启动程序编译

c++ - 是否可以将此 Rust 代码写入语义上等效的 C++ 代码?

c++ - 对具有相同参数签名的 operator[] 方法返回的 double 和 double 的引用

python - 新编写的 Django 管理器在模板中不起作用

c++ - 如何返回定义明确的内存部分?例如图像数据中像素的颜色值