gpt4 book ai didi

C++ 函数指针作为模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:17:09 28 4
gpt4 key购买 nike

我对下面的代码片段有疑问,不确定我是否正确理解这些代码。

template <typename R, typename... Args>                                     
class RunnableAdapter<R(*)(Args...)> {
public:
typedef R (RunType)(Args...);

explicit RunnableAdapter(R(*function)(Args...))
: function_(function) {
}

R Run(Arg... args) {
return function_(args...);
}

private:
R (*function_)(Args...);
};
  1. <R(*)(Args...)>是一种“函数指针类型”并且 R 和 (*) 之间的闪烁空间不一定是必需的?

  2. RunnableAdapter 的实例化是什么?我假设它如下所示。
    void myFunction(int i){ // };
    RunnableAdfapter<(void)(*)(int)> ra(MyFunction);
    ra.Run(1); //which calls MyFunction(1)

最佳答案

起初您提供的代码有一些错误,甚至无法编译。回答您的问题:

  1. 空格不是必需的。
  2. 看下面的例子

你可以这样声明你的类

template <typename T>
class RunnableAdapter;

template <typename R, typename... Args>
class RunnableAdapter<R(*)(Args...)> { ... }

并实例化它

RunnableAdapter<void(*)(int)> ra(&myFunction);

但你可以简化它(这里是完整的工作示例)

#include <iostream>
#include <string>

template <typename T>
class RunnableAdapter;

template <typename R, typename... Args>
class RunnableAdapter<R (Args...)> {
public:

explicit RunnableAdapter(R(*function)(Args...))
: function_(function) {
}

R Run(Args... args) {
return function_(args...);
}

private:
R (*function_)(Args...);
};

void myFunction(int i){ std::cout << i << std::endl; }

int main()
{
RunnableAdapter<void(int)> ra(&myFunction);
ra.Run(1);
}

这将允许使用类似签名的表达式进行实例化,例如 void(int)。它看起来更好,不需要 (*)

还有另一种方法是不进行类特化,就像这样。结果是一样的,只是类声明和实例化略有不同。

#include <iostream>
#include <string>

template <typename R, typename... Args>
class RunnableAdapter {
public:

explicit RunnableAdapter(R(*function)(Args...))
: function_(function) {
}

R Run(Args... args) {
return function_(args...);
}

private:
R (*function_)(Args...);
};

void myFunction(int i){ std::cout << i << std::endl; }

int main()
{
RunnableAdapter<void, int> ra(&myFunction);
ra.Run(1);
}

编辑

正如@Jarod42 所建议的,最好像这样制作Run

template<typename... Ts>
R Run(Ts&&... args) {
return function_(std::forward<Ts...>(args)...);
}

关于C++ 函数指针作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954568/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com