Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain this C++ typedef?

Tags:

c++

typedef

I've just started working with C++ after not having worked with it for quite a while. While most of it makes sense, there are some bits that I'm finding a bit confuddling. For example, could somebody please explain what this line does:

typedef bool (OptionManager::* OptionHandler)(const ABString& value);
like image 978
David Johnstone Avatar asked Feb 17 '10 05:02

David Johnstone


People also ask

What's the point of typedef?

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.

Can you typedef a typedef?

Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again.

Should I use typedef in C?

Code Clarity:In the case of the structure and union, it is very good to use a typedef, it helps to avoid the struct keyword at the time of variable declaration. You can also give a meaningful name to an existing type (predefined type or user-defined type).

What is typedef structure in C?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.


2 Answers

It defines the type OptionHandler to be a pointer to a member function of the class OptionManager, and where this member function takes a parameter of type const ABString& and returns bool.

like image 136
sth Avatar answered Sep 30 '22 07:09

sth


typedef bool (OptionManager::* OptionHandler)(const ABString& value);

Let's start with:

OptionManager::* OptionHandler

This says that ::* OptionHandler is a member function of the class OptionManager. The * in front of OptionHandler says it's a pointer; this means OptionHandler is a pointer to a member function of a class OptionManager.

(const ABString& value) says that the member function will take a value of type ABString into a const reference.

bool says that the member function will return a boolean type.

typedef says that using "* OptionHandler" you can create many function pointers which can store that address of that function. For example:

OptionHandler fp[3];

fp[0], fp[1], fp[2] will store the addresses of functions whose semantics match with the above explanation.

like image 29
Vijay Avatar answered Sep 30 '22 07:09

Vijay