gpt4 book ai didi

c++ - 在 C++ 中,我可以使用箭头运算符访问另一个运算符吗?

转载 作者:行者123 更新时间:2023-11-30 05:29:40 26 4
gpt4 key购买 nike

我有一个指向某个仿函数的指针。

class Functor {
public:
double operator()(int arg) {
return 0;
}
};

Functor* functorInstance = new Functor();

我必须这样调用它吗?

double result = (*functorInstance)(arg);

或者在这种情况下有什么方法可以使用 -> 吗?

最佳答案

如果它是一个 FUNCTOR,而不是你之前所说的函数,你可以使用 -> 语法调用它,你需要做的是 functor->operator()(args)。

如果您想将函数转换为仿函数,您可以这样编写模板:

#include <iostream>

template <typename ret_t, typename... args_t>
class myfunctor{

private:
ret_t (*funct)(args_t...);

public:
myfunctor (ret_t (*function)(args_t...)){
funct = function;
}

ret_t operator()(args_t... args){ return (*funct)(args...);}
};


int test(int a){
std::cout << a << std::endl;
return a;
}


int main(){
myfunctor<int, int> t(&test);
t(3);
myfunctor<int, int> * t2 = new myfunctor<int, int>(&test);
t2->operator()(3);
(*t2)(3);

}

关于c++ - 在 C++ 中,我可以使用箭头运算符访问另一个运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309196/

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