Permalink
Browse files

Add named_parameters project.

Signed-off-by: Thiago Farina <tfarina@chromium.org>
  • Loading branch information...
1 parent abbf3d8 commit d7a2a5e1422c810022fbeec16d38bf8fa473dee0 @tfarina committed Feb 17, 2013
@@ -0,0 +1,10 @@
+#include "timer.h"
+
+using apibook::Timer;
+
+int main(int, char **) {
+ // The NPI lets you create method chains to simulate optional params.
+ Timer timer = Timer().SetDelay(10.0).SetSingleShot(true).Start();
+
+ return 0;
+}
@@ -0,0 +1,13 @@
+{
+ 'targets': [
+ {
+ 'target_name': 'named_parameters',
+ 'type': 'executable',
+ 'sources': [
+ 'main.cc',
+ 'timer.cc',
+ 'timer.h',
+ ],
+ },
+ ],
+}
@@ -0,0 +1,52 @@
+#include "timer.h"
+
+#include <iostream>
+
+namespace apibook {
+
+class Timer::Impl {
+ public:
+ float delay;
+ bool singleshot;
+};
+
+Timer::Timer()
+ : impl_(new Timer::Impl) {
+ impl_->delay = 0.0f;
+ impl_->singleshot = false;
+}
+
+Timer::~Timer() {
+ delete impl_;
+ impl_ = NULL;
+}
+
+Timer::Timer(const Timer &other)
+ : impl_(new Timer::Impl) {
+ impl_->delay = other.impl_->delay;
+ impl_->singleshot = other.impl_->singleshot;
+}
+
+const Timer &Timer::operator =(const Timer& other) {
+ impl_->delay = other.impl_->delay;
+ impl_->singleshot = other.impl_->singleshot;
+ return *this;
+}
+
+Timer& Timer::SetDelay(float t) {
+ impl_->delay = t;
+ return *this;
+}
+
+Timer& Timer::SetSingleShot(bool ss) {
+ impl_->singleshot = ss;
+ return *this;
+}
+
+Timer& Timer::Start() {
+ std::cout << "Start timer: delay = " << impl_->delay;
+ std::cout << ", single-shot = " << impl_->singleshot << std::endl;
+ return *this;
+}
+
+} // namespace apibook
@@ -0,0 +1,31 @@
+#ifndef CHAPTER4_DESIGN_NAMED_PARAMETERS_TIMER_H_
+#define CHAPTER4_DESIGN_NAMED_PARAMETERS_TIMER_H_
+
+namespace apibook {
+
+// A simple class that demonstrates the Named Parameter Idiom.
+class Timer {
+ public:
+ Timer();
+ ~Timer();
+
+ // Allow this class to be copyable
+ Timer(const Timer&);
+ const Timer& operator =(const Timer&);
+
+ // An NPI-style setter for the timer delay
+ Timer& SetDelay(float t);
+ // An NPI-style setter for whether the timer repeats
+ Timer& SetSingleShot(bool ss);
+
+ // Start the timer with the current settings
+ Timer& Start();
+
+ private:
+ class Impl;
+ Impl* impl_;
+};
+
+} // namespace apibook
+
+#endif // CHAPTER4_DESIGN_NAMED_PARAMETERS_TIMER_H_

0 comments on commit d7a2a5e

Please sign in to comment.