gpt4 book ai didi

c++ - 将任何类型的参数附加到事件

转载 作者:太空宇宙 更新时间:2023-11-04 11:43:25 24 4
gpt4 key购买 nike

我对泛型编程的经验很少(我很少需要它),但我现在正在尝试为我的应用程序实现一个事件系统。这是我对实际事件的想法:

template <typename Arg_Type> struct Event {
std::vector<std::string> ids; // All the objects to pass the event to
Action action; // Action to perform (enum)
std::vector<Arg_Type> args; // List of event-dependant arguments
};

但是我想将我的各种事件存储在一个 vector 中:

std::vector<Event*> events;

不幸的是,它似乎并没有那么简单!

我将如何实现预期的效果?也就是说,能够传递具有各种参数类型的事件?

我知道我可以做这样的事情:

struct Event {};

struct EventFloat : public Event {};

struct EventString : public Event {};

但它看起来不够优雅且难以维护。

最佳答案

让你的Event<>类继承自一个共同的父类,例如 EventInterface . EventInterface将是定义所有事件接口(interface)的抽象类。

class EventInterface
{
public:
virtual void tweak ( int t ) = 0;
virtual void twiddle( int t ) = 0;
virtual void frob ( int f ) = 0;

virtual ~EventInterface() {};
};

template <typename Arg_Type> struct Event : public EventInterface {
};

然后让你的 vector 成为一个std::vector<EventInterface *>等等。

从维护的角度来看,它并没有那么糟糕,因为公共(public)接口(interface)类所做的只是为所有要遵守的事件定义一个公共(public)接口(interface)。如果您确实想添加新的非模板事件类,您也可以。

缺点是你不能制作ArgType通用接口(interface)的一部分。然而,这在一定程度上是有道理的:你还能如何合法地在 Event* 上调用任意方法?如果您不知道参数的类型?

现在您可以要求所有 Arg_Type是一些常见的子类 EventArgument类,并据此定义您的接口(interface)。该模板仍然会给您带来一些好处。这完全取决于您要如何定义事件接口(interface)。

工作示例:

class EventArgument 
{
public:
virtual int getId () = 0;
virtual ~EventArgument() { };
};

class EventInterface
{
public:
virtual void tweak ( int t ) = 0;
virtual void twiddle( int t ) = 0;
virtual void frob ( int f ) = 0;
virtual EventArgument& getArg() = 0;

virtual ~EventInterface() {};
};

class fredArg : public EventArgument
{
public:
virtual int getId() { return 1; }
~fredArg() { };
};
class barneyArg : public EventArgument
{
public:
virtual int getId() { return 2; }
~barneyArg() { };
};

template <typename Arg_Type>
struct Event : public EventInterface
{

Arg_Type arg;

Event() { };

virtual void tweak ( int t ) { };
virtual void twiddle( int t ) { };
virtual void frob ( int f ) { };

virtual EventArgument& getArg()
{
return arg;
}
};

#include <vector>
#include <iostream>

std::vector<EventInterface*> events;

int main()
{
events.push_back( new Event<fredArg>( ) );
events.push_back( new Event<barneyArg>( ) );

std::cout << events[0]->getArg().getId() << std::endl;
std::cout << events[1]->getArg().getId() << std::endl;
}

这会打印出 12如您所料。

关于c++ - 将任何类型的参数附加到事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557252/

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