Option Three
Sobering time.
Cold head. May I remind you we all know very well about the good old Function Object aka “Functor”?
So let’s do a proverbial step back and use what we already know. Bellow is a very bland-looking very traditional C++ solution. I am not sure but perhaps even the C++98 compiler could produce a decent byte code from this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* No stunts. A plain old function object. Simple usable and working */ template<typename T> class holder { // mutable members of const class instances are modifiable mutable T default_value_{}; public: holder(const T & defval_) : default_value_(defval_) { }; // we will be overloading the operator () // aka the call operator const T & operator () () const noexcept { return default_value_; } /* The operator overload bellow allows for const isntances to be used through the operator bellow const holder<REAL> width{ 10 }; width(1024) ; // OK */ const T & operator () (const T & new_ ) const noexcept { if (new_ != default_value_) default_value_ = new_; return default_value_; } }; |
Testing begins here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
namespace { using namespace Gdiplus; // test the const behaviour // and prepare the default width holder const holder<REAL> width{ 10 }; holder<SmoothingMode> smoothnes{ SmoothingMode::SmoothingModeAntiAlias }; holder<LineCap> linecap{ LineCap::LineCapRound }; inline void usage() { //change the default width from 10 to 1024 width( 1024 ); // read it const auto w1_ = width(); auto w2_ = width(); assert(w2_ == w1_ == 1024); // and so on woth other GDI+ use cases auto lc_ = linecap(); auto sm_ = smoothnes(); } } // ns |
I think this is one sober solution indeed. And working too. Usage seems simple and with no surprises.
Also, the default argument issue is solved in the C++ way. Modern or not. By using () operator overload, on the class.
What also is delivered is correct behavior in case of const required. Code above is documented. And easy to maintain, expand or do whatever might be required down the line.