woodenToaster
woodenToaster

Reputation: 274

Does this typedef mean what I think it does?

I believe I understand this, but I would like some confirmation.

typedef int (NewTypeName) (arg_type* t);

To my undestanding, this type definition allows one to easily declare functions that take 1 argument of type arg_type* and return an int. To declare these functions in a header file, one would write:

NewTypeName func1;
NewTypeName func2;

However, when defining these functions in the .cpp file, I would do it like this:

int func1(arg_type* t) {
  //do something
  return 1;
}

Am I understanding this correctly?

Upvotes: 1

Views: 300

Answers (2)

user743382
user743382

Reputation:

Yes, it means exactly what you think it means, and yes, that typedef can be used only for a declaration that is not a definition.

Note that the parentheses are unnecessary and unusual here: a more common way to write this is

typedef int NewTypeName (arg_type* t);

The parentheses are only required when you want a pointer-to-function typedef:

typedef int (*NewTypeName) (arg_type* t);

As the comment on your question shows, what you have is very easily misread.

Such typedefs are almost always unnecessary, although they can increase readability when dealing with pointer-to-function parameter or return types: the C function signal can be declared as

typedef void sighandler(int);
sighandler *signal(int signum, sighandler *handler);

or as

typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler);

or as

void (*signal(int sig, void (*func)(int)))(int);

You tell me, which is more readable? I'm guessing you won't choose the third option.

There is one case where the use of a typedef is required: although commonly unimplemented in compilers, C++ compilers are supposed to treat functions with C linkage as different types from functions with C++ linkage. The linkage of names is universally implemented, but the linkage of types is rare. It can be useful to have a template function, which cannot have C linkage, but still give it a type that does have C linkage. This requires a typedef:

extern "C" {
typedef void func_t();
};
template <typename> func_t myfunc;
template <typename T> void myfunc(void) { /* your definition here */ }

Upvotes: 5

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

That's exactly right, but you should really never declare functions like that. It'll only serve to confuse people. The problem is that there's no way to define a function using the typedef, so the declarations and definitions are inconsistent.

Upvotes: 2

Related Questions