Monday, July 20, 2009

Named Parameter Idiom

C++ supports only positional parameters and not parameters mapping.


Solution:

The idea, called the Named Parameter Idiom, is to change the function's parameters to methods of a newly created class, where all these methods return *this by reference. Then you simply rename the main function into a parameterless "do-it" method on that class.

Wraps all parameter into member function of a class and its required parameters as private member.


class File;



class OpenFile {

public:

OpenFile(const std::string& filename);

// sets all the default values for each data member

OpenFile& readonly(); // changes readonly_ to true

OpenFile& readwrite(); // changes readonly_ to false

OpenFile& createIfNotExist();

OpenFile& blockSize(unsigned nbytes);

...

private:

friend class File;

std::string filename_;

bool readonly_; // defaults to false [for example]

bool createIfNotExist_; // defaults to false [for example]

...

unsigned blockSize_; // defaults to 4096 [for example]

...

};



inline OpenFile::OpenFile(const std::string& filename)

: filename_ (filename)

, readonly_ (false)

, createIfNotExist_ (false)

, blockSize_ (4096u)

{ }



inline OpenFile& OpenFile::readonly()

{ readonly_ = true; return *this; }



inline OpenFile& OpenFile::readwrite()

{ readonly_ = false; return *this; }



inline OpenFile& OpenFile::createIfNotExist()

{ createIfNotExist_ = true; return *this; }



inline OpenFile& OpenFile::blockSize(unsigned nbytes)

{ blockSize_ = nbytes; return *this; }

class File {

public:

File(const OpenFile& params);

...

};

No comments: