[alicebot-developer] Dynamic tag instantiation in C++ (was: ChatterBean 00.007 is now available)

Helio Perroni Filho xperroni at yahoo.com
Sun Dec 11 03:16:27 PST 2005


--- mehri <foreverlinux at yahoo.com> escreveu:

> Problem is that from the xml I get the AIML tag name
> as a String.  From the string I have to instantiate
> the class with the same name.

Hence my idea of providing factory functions for each
tag, mapping the tag names to pointers for the factoy
functions, and then retrieving the pointers from a map
as the tags are read from the XML document. As I
exposed, it is not as simple as reflection, but it can
be done, and is more efficient than conditional
chains.

> I know of a few ways but none are elegant and all
> are more complex then simply registering the classes
in
> a factory method:
> 
> Tag &tagClass createClass(String someClassName)
> {
>   if(someClassName == "InnerTemplate")
>       return new InnerTemplate;
>   else if(someClassName == "xxx")
>       return new XXX
> }

The problem with this approach is that you have to
modify the factory method each time you add a new tag.
With a global factory map, however, you could demand
each new tag to register itself at loading time:

// aiml.h

// Global field.
map<String, FactoryFunction> factories;

// ...

// category.h

#include <aiml>

class Category
{
  // ...
}

Tag& newCategory()
{
  return new Category();
}

// Ugly hack to allow load-time execution of code.
class CategoryRegister
{
public:
  CategoryRegister()
  {
    factories["Category"] = newCategory;
  }
}

// Makes the class constructor be called at loading
time.
CategoryRegister& categoryRegister;

-- 
Ja mata ne.
Helio Perroni Filho



	



	
		
_______________________________________________________ 
Yahoo! doce lar. Faça do Yahoo! sua homepage. 
http://br.yahoo.com/homepageset.html 



More information about the alicebot-developer mailing list