C ++ function pointer type call pattern

If I have type type declarations

typedef void (*command)(); template <command c> void execute() { c(); } void task() { /* some piece of code */ } 

then

 execute<task>(); 

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

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

it is still compiling. I did it by accident. Now I'm confused by what is expected from the second version.

+7
c ++ templates
source share
2 answers

In c ++

 type_name() 

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

For native types, there are implicitly defined default constructors, therefore, for example,

 int(); 

is a valid C ++ operator (just creates an int and discards it).

g++ with full warnings about emitting a diagnostic message because it is a suspicious (possibly unintentional) operation, but the code is valid and there may even be programs depending on it (if the type is a user-defined type and the instance constructor has side effects).

+8
source share
 command(); 

Creates a temporary object such as TYPE(); , and the compiler omits it as an unused variable.

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

You must enable the -Wall compiler -Wall . Living code.

+4
source share

All Articles