Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C++ by Grey ( 17 years ago )
#include <iostream>
using namespace std;

// ----------------------------------------------------
// Functor
class GetData
{
public:
	// Init the pointer with the run-once function  
	GetData()
	{ pfunc_ = &GetData::do_first; };

	// Call a worker member function by the pointer	
	inline int operator()(int param)
	{ return (this->*pfunc_)(param); };

private:
	// Pointer to a worker member function
	int (GetData::*pfunc_)(int);

	// Run-once worker function
	int do_first(int param)
	{
		cout << "First time call with parameter " << param << ". Do some extra init work.
";
		// ... Do some extra work, e.g. a system call to get some data...
		// ... Do normal work then ...

		// Change the pointer to the normal worker function
		pfunc_ = &GetData::do_normal;

		return param;
	};

	// Run-all-other-time worker function
	int do_normal(int param)
	{
		cout << "Normal call with parameter " << param << ", without extra work and conditional operators.
";
		// ... Do normal work only...
		return param;
	};

} get_data;

// ----------------------------------------------------
// Let's main
int main()
{
	get_data(1);

	// Somewhere far away...
	get_data(2);

	// Somewhere in other source file...
	get_data(3);

	return 0;
}

 

Revise this Paste

Your Name: Code Language: