将C ++函数作为参数传递,而不使用函数指针/内联? [英] Passing C++ functions as arguments without function pointer/inlined?

查看:137
本文介绍了将C ++函数作为参数传递,而不使用函数指针/内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递函数的正确方法(使用相同的输入参数/返回类型)作为另一个函数的参数,而不使用函数指针?我希望传入的函数参数在被调用时被内联?那么,我只是不希望指针间接。



我发现这个:

传递函数作为显式模板参数



但它似乎是使用函数指针。

编辑:我真的很想避免必须创建结构来存储每个函数参数的行为。

解决方案

如果您在编译时知道专业化,您只需传递类型信息:

  void inlined_function(){}; //你想传递的函数

模板< typename F> void caller1(){
inlined_function(); //不通过指针,调用内联
}

如果你有内联控制函数,将其实现为一个仿函数:

pre $ $ $ $ $ $ $ $ $ inline void operator()()//内联函数
{
}
};

模板< typename F> void caller2(F functor){
functor(); //内联调用
}

两种变体的客户端代码:

  caller1< inlined_function>(); 
caller2(X {});

编辑

如果您没有控制权将函数作为结构写入,请为其编写一个内联结构包装函数。



例如,您有 void inlined_function(){}; 并需要写入 caller2 。在这种情况下,编写一个类似于 X 的函数,它调用 inlined_function ,或者(更好)lambda:

 模板< typename F> void caller2(F functor){
functor(); // inline call
}

caller2([](){inlined_functor();});


What is the correct way to pass functions (with the same input arguments/return type) as arguments to another function, without function pointers being used? I would like the function argument passed in to be inlined when it is called? Well, I just don't want the pointer indirection.

I found this:

Pass a function as an explicit template parameter

but it seems to be using function pointers.

EDIT: I'd really really really like to avoid having to create structs to store the behaviour for each function argument.

解决方案

If you know the specialization at compilation time, you just need to pass type information:

void inlined_function() {}; // function you want to pass

template<typename F> void caller1() {
    inlined_function(); // not passed through pointer, call inline
}

If you have control of the inline function, implement it as a functor:

struct X {
    inline void operator()() // inline function
    {
    }
};

template<typename F> void caller2(F functor) {
    functor(); // inline call
}

Client code for the two variants:

caller1<inlined_function>();
caller2(X{});

Edit:

If you do not have control to write the functor as a structure, write an inline structure wrapper for it.

E.g., you have void inlined_function() {}; and need to write caller2. In this case, write a functor similar to X that calls inlined_function, or (better yet), a lambda:

template<typename F> void caller2(F functor) {
    functor(); // inline call
}

caller2( [](){ inlined_functor(); } );

这篇关于将C ++函数作为参数传递,而不使用函数指针/内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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