是否有一个基于宏的适配器从类创建函子? [英] Is there a macro-based adapter to make a functor from a class?

查看:131
本文介绍了是否有一个基于宏的适配器从类创建函子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建函子需要一个不必要的锅炉板。该状态必须写入4次!

Creating a functor requires an unnecessary boiler plate. The state has to be written 4 times!

struct f{
  double s; // 1st
  f(double state): s(state) {} // 2nd, 3rd and 4th
  double operator() (double x) {
    return x*s;
  }
};

是有一个宏的库,只是 double functor )(x){return x * state; } 或类似的东西。

is there a library with a macro that would be just double functor(state)(x){ return x*state; } or something similar.

BOOST_FOREACH 是一个工作良好的宏适配器。我在寻找类似的东西。

BOOST_FOREACH is a macro adapter that works well. I'm looking for something similar.

任何关于如何写一个建议也是赞赏。

any suggestions on how to write one is appreciated too.

ps。使用struct for functor更快,然后绑定 Class的operator()或bind作为函子的函数?

ps. using struct for functor is faster then bind Class's operator() or bind a function as a functor?

更新(1)

关于lambdas:

函数必须是模块化的,意味着它应该可以在其他函数中重用。 lambdas必须在一个函数内 - lambda必须在main和main以外的其他函数中被调用,不能调用main中定义的lambda。

the functor has to be modular, meaning, it should be reusable in other function. lambdas have to be within a function -- lambda has to be in main to be called from main and other functions outside of main, can't call the lambda defined in main.

推荐答案

如何依赖聚合初始化?只是不声明构造函数:

How about relying on aggregate initialization? Simply do not declare the constructor:

struct f {
    double s;
    double operator()(double x) {
        return x * s;
    }
};

使用它

int main()
{       
    auto ff = f{42};
    std::cout << ff(2);
    return 0;
}

这篇关于是否有一个基于宏的适配器从类创建函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆