Udo Klein
Udo Klein

Reputation: 6882

c++ template call of function pointer type

If I have type declarations like

typedef void (*command)();

template <command c>
void execute() {
   c();
}

void task() { /* some piece of code */ }

then

execute<task>();

will compile and behaves as expected. However if I define the template as

template <command c>
void execute() {
   command();
}

it still compiles. I did this by accident. Now I am confused of what the second version would be expected to do.

Upvotes: 7

Views: 179

Answers (2)

masoud
masoud

Reputation: 56479

command();

It creates a temporary object like TYPE(); and compiler omits it as an unused variable.

warning: statement has no effect [-Wunused-value]
     command();
     ^

You should turn on -Wall compiler's option. Live code.

Upvotes: 4

6502
6502

Reputation: 114481

In C++

type_name()

is an expression that creates a default-initialized instance of type_name.

For natives types there are implicitly defined default constructors, so for example

int();

is a valid C++ statement (just creates an int and throws it away).

g++ with full warnings on emits a diagnostic message because it's a suspect (possibly unintended) operation, but the code is valid and there can even be programs depending on it (if the type is a user-defined type and the constructor of the instance has side effects).

Upvotes: 8

Related Questions