将任何函数作为模板参数 [英] Passing any function as template parameter

查看:114
本文介绍了将任何函数作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个函数 value 作为函数的模板参数。目前我最好设法做的是:

I want to pass a function value as a template parameter to a function. Currently the best I managed to do is :

template< typename F, F f >
void pass()
{
    ...
}


$ b b

...用于:

...which is used:

pass< decltype(&func), &func >();

我真正想要的是:

pass< &func >();

有没有办法实现这个没有宏?基本上同时传递类型和值?编译器显然拥有所需的所有信息...

Is there any way to achieve this without macros? Basically to pass both the type and the value at the same time? The compiler obviously has all the information needed for that...

解决方案必须使用变量参数和返回类型。函数值在编译时使用,因此不能作为参数传递。

The solution must work with variable parameters and return types. The function value is used at compile time, so it cannot be passed as an argument.

欢迎使用C ++ 11解决方案。

C++11 solutions welcome.

Edit: use case - 我在编译时生成绑定,我需要为每个传递的函数创建一个C ++函数。这个代码的用例看起来(简化)大致如下:

use case - I'm generating bindings at compile-time, where I need to create a C++ function for each passed function. The use case of this code looks (simplified) more or less like this:

template < typename F, F f > 
int function_wrapper( lua_State* L ) 
{
    return dispatcher<typename return_type<F>::type>::call( L, 1, f );
}

void register_native_function( lua_Function f, const char* name )
{
    // binding call using pure C function f
}

template < typename F, F f >
void register_function( const char* name )
{
    register_native_function( function_wrapper< F, f >, name );
}



请注意,我需要创建一个编译时函数包装器在编译时需要传递函数值。有些绑定解决方案允许在运行时绑定,但是与手写绑定相比,它们总是需要样板代码。我的目标是在这里实现一个手写的表现。

Please note that I need to create a compile-time function wrapper, so I need the pass function value at compile time. There are binding solutions that allow binding at runtime, but they always require boilerplate code compared to hand-written bindings. I'm aiming to achieve a hand-written performance here.

推荐答案

我相信缩短这是目前不可能。一年前,C ++委员会查看了 http://www.open -std.org/jtc1/sc22/wg21/docs/papers/2013/n3601.html 来解决这个问题,他们鼓励作者在C ++ 14发布后继续进一步。

I believe shortening this is currently impossible. A year ago, the C++ committee looked at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3601.html to fix this, and they encouraged the authors to pursue it further after C++14 was released.

这篇关于将任何函数作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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