Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'X x; x();' allowed, when 'X' defines a conversion to function pointer, but not, when it defines a conversion to a functor?

People also ask

How do you define a pointer to a function?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions.

What Cannot be done with function pointer?

What will we not do with function pointers? Explanation: As it is used to execute a block of code, So we will not allocate or deallocate memory.

What is a function pointer that allows you to invoke a procedure in directly?

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory.

Is it possible to declare function pointers?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.


x(5); // works ?!

This implicitly casts x to an f_ptr and calls that. C++11 standard:

§ 13.3.1.1.2 Call to object of class type [over.call.object]

2) In addition, for each non-explicit conversion function declared in T of the form

operator conversion-type-id ( ) attribute-specifier-seqopt cv-qualifier ;

[…where conversion-type-id denotes the type “pointer to function of (P1,...,Pn) returning R”…]


y(5); // doesn't ?!

The standard doesn't mention anything about implicit conversion to class types that overload operator() (aka functors), which implies that the compiler doesn't allow that.

You must cast it explicitly:

static_cast<Functor>(y)(5);