如何将函数集合传递给客户端类,以便将它们当作客户端类本身的成员使用

  • 本文关键字:客户端 成员 集合 函数 c++
  • 更新时间 :
  • 英文 :


我有带有一些方法的接口IFuncs(理想情况下,这些方法是静态的,但我没有找到提供静态方法接口的好方法-有什么建议吗?(。这可以被认为是一个"函数集合"。

有一个类Client,它在内部使用该接口的具体实现,在构造时传递。

Bellow,一个有想法的代码(不编译(。

我想知道如何实现这一目标的建议。

附言:如果Client可以像调用Client类本身的成员一样调用IFuncs(具体(方法,那就太好了(如下面的代码所示(。

#include <iostream>
using namespace std;
// Interface for a class with some methods (ideally these methods would be static, but I've found no way to provide a interface to static methods)
class IFuncs {
public:
virtual int fa(int a, int b) = 0;
/* other functions */
};
// Implementation "X"
class FuncsX: public IFuncs {
public:
int fa(int a, int b) {
return a + 2*b;
}
};
// Implementation "Y"
class FuncsY: public IFuncs {
public:
int fa(int a, int b) {
return 3*a - b;
}
};
// alias for the type IFuncs::fa()
using fa_t = int (IFuncs::*)(int, int);
// Class that uses an implementation of IFuncs, passed to the constructor
class Client {
public:
fa_t fa; // reference/pointer to a function IFuncs::fa()
Client(const IFuncs& arg_funcs) : fa(arg_funcs.fa) {
}
void do_something(int a, int b) {
// call fa() as it was a function member of this Class
cout << fa(a, b) << "n";
}
};
int main(int argc, char **argv) {
FuncsX funcsx;
FuncsY funcsy;

Client c1(funcsx);
Client c2(funcsy);
cout << c1.fa(3, 4) << "n";
cout << c2.fa(3, 4) << "n";
return 0;
}

我有一个稍微不同的解决方案,它有优点和优点;缺点(这个解决方案适用于C++20,但如果你需要,它可以简单地转换为C++11(:

template<typename T> concept IFuncsInterface = std::is_base_of_v<IFuncs, T>; // Define a rule to force the type to inherit from IFuncs interface. If not it'll throw a compilation error.
// Class that uses an implementation of IFuncs, passed as template parameter
template <IFuncsInterface Funcs>
class Client : public Funcs { // Inherit from given type
public:
Client() {}
void do_something(int a, int b) {
// call fa() as it was a function member of this Class
cout << this->fa(a, b) << "n"; // Working!
}
};
int main(int argc, char **argv) {
Client<FuncsX> c1; // Inherit from FuncsX
Client<FuncsY> c2; // Inherit from FuncsY
cout << c1.fa(3, 4) << "n";
cout << c2.fa(3, 4) << "n";
return EXIT_SUCCESS;
}

优点

  1. 您不必创建指向IFuncs接口中每个函数的指针
  2. 在容器函数中没有混乱的情况下清理解决方案-不必为每个想要创建ClientIFuncs子对象保留一个对象

缺点

  1. 根据你的类目的,这在逻辑上可能是错误的
  2. 如果您已经在某个地方有了IFuncs派生类,并且定义了要使用的属性,那么使用此解决方案,您将无法将它们应用到Client类中(除非您要实现某种集合函数(

参考文献

我最近实现了这样的东西,你可以在那里看到我的想法:CppDecoratorDesignPattern(它不是一个真正的装饰器设计模式,但对我来说已经足够接近了:p(。为了实现这一点,我在下面的帖子中得到了@RaymondChen的帮助,你可以从中获得更多想法:在C++中迭代类继承。

相关内容

最新更新