autobahn
autobahn

Reputation: 115

What does the single asterisk inside parentheses "(*)" do in C++?

I found code that looks like this:

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

and after searching for a while, I still can't figure out what the (*) operator does exactly. Anyone have any ideas?

Upvotes: 5

Views: 1348

Answers (4)

fredoverflow
fredoverflow

Reputation: 263350

You can make complicated pointer types a lot less confusing in C++11 thanks to template typedefs:

template<typename T> using ptr = T*;

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

Upvotes: -1

It's a function pointer declaration.

This typedef means the std::map is mapping strings to function pointers, that receives void and returns Example*.

You could use it like this:

#include <string>
#include <map>

typedef  int Example;

Example* myExampleFunc() {
    return new Example[10];
};

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

int main() {

    map_type myMap;
    // initializing
    myMap["key"] = myExampleFunc;

    // calling myExampleFunc

    Example *example = myMap["key"]();

    return 0;
}

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613521

The parens here are use to impose precedence. The type

Example*(*)()

is a pointer to function returning pointer to Example.

Without the parens you would have

Example**()

which would be a function returning pointer to pointer to Example.

Upvotes: 7

This is the syntax used to declare a pointer to a function (your case) or an array. Take the declaration

typedef Example* (*myFunctionType)();

this will make the line

typedef std::map<std::string, myFunctionType> map_type;

be exactly equivalent to the line you've given. Note that the difference between Example* (*myFunctionType)() and Example* (*)() is only that the name of the type has been omitted.

Upvotes: 5

Related Questions