Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is Base*(*)()

Tags:

c++

templates

stl

Can someone please explain the Base*(*)() for me as in:

typedef std::map<std::string, Base*(*)()> map_type;

And how would one return it from a function?

I presume it is a function pointer, a Base* is returned, but what is this (*).

I found this in the following SO post Is there a way to instantiate objects from a string holding their class name?

Thanks

like image 226
Steven ZA Avatar asked May 13 '26 09:05

Steven ZA


2 Answers

Base* (*)() is a type: pointer to function returning Base*. The * means that it is a pointer and the () are used to to override the precedence to ensure that the pointer applies to the function itself and not the return type.

You can return it from a function by returning the name of a function of the appropriate type.

E.g.

Base* f();

Base* (*g())()
{
    return f;
}
like image 76
CB Bailey Avatar answered May 16 '26 00:05

CB Bailey


It's the type of a function pointer of a function of signature Base*():

Base * foo();

Base * (*fp)() = &foo;

Or in your case:

map_type callbacks;
callbacks["Foo"] = &foo;

To invoke:

Base * p = callbacks["Foo"]();  // same as "p = foo();"
like image 42
Kerrek SB Avatar answered May 16 '26 00:05

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!