Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Templated return

I have a program which is built on "Entities", which hold "Components" (composition FTW).

Components may include many different types including scripts, assets, etc. I would like to build an Entity function called

Entities have a map of strings, and actual Components, such that the Components can be searched for by type name.

I would like to have a function called

<Component T>GetComponent(char* TypeName, <T>);

Which takes in a string and a type name, and which returns the typed component that is requested.

Is it possible to do such a thing with C++ templates? The above clearly does not work, and I'm not sure how to go about it.

Thanks

Edit:

I'm not looking for a factory.

Entity holds instances of different types of components. Currently this is done with

std::vector<Component> componentList; 

and an

std::vector<char*> componentNames; 

Whose indexes are guaranteed to be the same. Likely I will write a proper map later.

I simply want GetComponent to return a properly typed reference to the already instantied component of type name held by Entity in the ComponentList.

like image 498
mjames Avatar asked Sep 15 '26 08:09

mjames


1 Answers

Does your function create components? Then it is a factory. You could wrap it in that template in order to save clients the (potentially erroneous) casting.

The type of the function template would look like this:

template< typename T >
T* GetComponent(const char*); // presuming it returns a pointer

and it would be called like this:

Foo* foo = GetComponent<Foo>("foo");
like image 174
sbi Avatar answered Sep 17 '26 20:09

sbi