简体   繁体   English

Function 指针,具有“模板化”返回类型和 arguments

[英]Function pointer with “templated” return type and arguments

So I want to have a function which takes in a function pointer, with an "unknown" return type and arguments.所以我想要一个 function 接收一个 function 指针,具有“未知”返回类型和 arguments。 The function should return the same type as the function it recieves as a parameter. function 应该返回与它作为参数接收的 function 相同的类型。 I thought about something like this, but it isn't working:我想过这样的事情,但它不起作用:

template<typename type, typename... param>
type do_sth(type (*func)(param... args))
{
  // ...
  type ret = func(std::forward<param>(args)...);
  // ...
  return ret;
}

I do this because I have to execute some other functions before and after the function itself.我这样做是因为我必须在 function 本身之前和之后执行一些其他功能。

Is something like this even possible?这样的事情甚至可能吗? It is definately possible with defines (but without the return value).绝对可以使用定义(但没有返回值)。 But because they are not effected by namespaces I want to use a function.但是因为它们不受命名空间的影响,所以我想使用 function。

With define statement it would look like this (not returning anything):使用 define 语句,它看起来像这样(不返回任何内容):

#define do_sth(x) /*...*/\
                  x;\
                  /*...*/

You need to pass the function and the arguments separately:您需要分别通过 function 和 arguments :

template<typename type, typename... param>
type do_sth(type (*func)(param...), param... args)

Demo演示

Note that you will run into some troubles with implicit conversions if you do it this way.请注意,如果你这样做,你会遇到一些隐式转换的麻烦。

You can also accept the function by type directly, but getting the return type is a little more involved:您也可以直接按类型接受 function,但获取返回类型有点复杂:

template<typename F, typename... param>
std::invoke_result_t<F, param...> do_sth(F func, param... args)

std::invoke_result is C++17 (but there's also result_of in C++11). std::invoke_result是 C++17 (但在 C++11 中也有result_of )。 With this version, implicit conversions work just fine.在这个版本中,隐式转换工作得很好。

Demo演示

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

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