函数指针参数的自动返回类型?

时间:2022-08-23 16:03:05

I'm creating a templated function that takes in a function pointer, although I'm trying to simplify the syntax a little further.

我正在创建一个带有函数指针的模板化函数,尽管我正在尝试进一步简化语法。

So far I have something like:

到目前为止,我有类似的东西:

template< typename obj, typename ret, typename... args >
auto py_wrapped_func( ret (obj::*f)( args... ) )
{
    // Do some stuff with the function pointer.
}

The trouble is, sometimes the return type, ret, is crazy long. I'm wondering if there's a way to simplify this to something like:

麻烦的是,有时回归类型,ret,是疯狂的。我想知道是否有办法将其简化为:

template< typename obj, typename... args >
auto py_wrapped_func( decltype(auto) (obj::*f)( args... ) )
{
    // Do some stuff with the function pointer.
}

Obviously this doesn't compile - "decltype(auto) is not allowed in function prototype". Is there a better way to go about this?

显然这不会编译 - “函数原型中不允许使用decltype(auto)”。有没有更好的方法来解决这个问题?

I'm aware I could just template on the function type directly, but I'd prefer to avoid having to write out the template function type when using the template, or using decltype(&obj::func). I need the arguments args as template parameters to be explicit in the template anyway.

我知道我可以直接在函数类型上模板,但我更愿意避免在使用模板或使用decltype(&obj :: func)时写出模板函数类型。无论如何,我需要参数args作为模板参数在模板中是显式的。

I'm guessing the compiler needs to know about the function pointer type explicitly, and not just the object and some arguments. Am I asking too much? Maybe I am?

我猜测编译器需要明确地知道函数指针类型,而不仅仅是对象和一些参数。我问得太多了吗?也许我是?

1 个解决方案

#1


0  

This is perhaps a duplicate of this question.

这可能是这个问题的重复。

The arguments of the function cannot be provided via template parameter deduction, however the function can. A simple solution is to rearrange the template arguments as follows:

函数的参数不能通过模板参数推导提供,但函数可以。一个简单的解决方案是重新排列模板参数,如下所示:

template< typename... args, typename obj, typename ret >
auto py_wrapped_func( ret (obj::*f)( args... ) )
{
    // Do some stuff with the function pointer.
}

Now the object and return type can be inferred from the argument.

现在可以从参数推断出对象和返回类型。

I wasn't sure this would work with a variadic template argument on the left. However it seems to compile fine...

我不确定这会在左侧使用可变参数模板参数。但它似乎编译好...

#1


0  

This is perhaps a duplicate of this question.

这可能是这个问题的重复。

The arguments of the function cannot be provided via template parameter deduction, however the function can. A simple solution is to rearrange the template arguments as follows:

函数的参数不能通过模板参数推导提供,但函数可以。一个简单的解决方案是重新排列模板参数,如下所示:

template< typename... args, typename obj, typename ret >
auto py_wrapped_func( ret (obj::*f)( args... ) )
{
    // Do some stuff with the function pointer.
}

Now the object and return type can be inferred from the argument.

现在可以从参数推断出对象和返回类型。

I wasn't sure this would work with a variadic template argument on the left. However it seems to compile fine...

我不确定这会在左侧使用可变参数模板参数。但它似乎编译好...