Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template call of function pointer type

Tags:

c++

templates

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.

like image 533
Udo Klein Avatar asked Oct 27 '13 07:10

Udo Klein


2 Answers

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).

like image 160
6502 Avatar answered Oct 19 '22 02:10

6502


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.

like image 44
masoud Avatar answered Oct 19 '22 03:10

masoud