简体   繁体   English

函子结构的 C++ 类型

[英]C++ type for functor structs

I am trying to have a single variable with some type that can be assigned to some of the C++ standard functors (eg: std::plus , std::multiplies , etc...)我正在尝试使用可以分配给某些 C++ 标准函子的某种类型的单个变量(例如: std::plusstd::multiplies等...)

Here is the definition for std::plus (from this link ):这是std::plus的定义(来自此链接):

template <class T> struct plus : binary_function <T,T,T> {
  T operator() (const T& x, const T& y) const {return x+y;}
};

I tried我试过了

#include <functional>

std::binary_function<int, int, int> func = std::plus;

but it doesn't work.但它不起作用。 How do I define it properly?如何正确定义它?

A single variable to hold all kinds of callables with same signature is std::function<int(int,int)> .保存具有相同签名的各种可调用对象的单个变量是std::function<int(int,int)> Though the functors need to either have the template argument specified or deducde them from arguments:尽管仿函数需要指定模板参数或从参数中推断出它们:

std::function<int(int,int)> func2 = [](int a,int b){ return std::plus{}(a,b);};

or或者

std::function<int(int,int)> func = std::plus<int>{};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM