return a function pointer c++ code example

Example 1: c++ function return pointer to itself

// To some free-function
struct func_wrap
{
    using f_t = func_wrap(*)();
    f_t func;
    f_t operator()() const noexcept { return func; }
    operator f_t() const noexcept { return func; }
};

using func_t = func_wrap(*)();

// Function to wrap
func_wrap foo() { return func_wrap{foo}; }

func_t bar() { return foo(); }
func_t buz() { return foo()(); }

// Some functor
struct function
{
   function operator()() const noexcept
   {
       return function();
   }
};

function foo(int) { return function(); }
function bar(int) { return function()(); }
function buz(int) { return function()()(); }

Example 2: Function pointer C++

void one() { cout << "One\n"; }
void two() { cout << "Two\n"; }


int main()
{
	void (*fptr)(); //Declare a function pointer to voids with no params

	fptr = &one; //fptr -> one
	*fptr(); //=> one()

	fptr = &two; //fptr -> two
	*fptr(); //=> two()

	return 0;
}

Tags:

Cpp Example