Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you wanted this simpler approach generalize it so you can get more use out of it, instead of tailor it to a specific thing. Then the question is not "should I make a entire new class for this specific thing?" but "should I use my utilities?"; the latter is always yes. And utilities are always helpful.</p> <p>So make something like:</p> <pre><code>template &lt;typename T&gt; void check_range(const T&amp; pX, const T&amp; pMin, const T&amp; pMax) { if (pX &lt; pMin || pX &gt; pMax) throw std::out_of_range("check_range failed"); // or something else } </code></pre> <p>Now you've already got this nice utility for checking ranges. Your code, even without the channel type, can already be made cleaner by using it. You can go further:</p> <pre><code>template &lt;typename T, T Min, T Max&gt; class ranged_value { public: typedef T value_type; static const value_type minimum = Min; static const value_type maximum = Max; ranged_value(const value_type&amp; pValue = value_type()) : mValue(pValue) { check_range(mValue, minimum, maximum); } const value_type&amp; value(void) const { return mValue; } // arguably dangerous operator const value_type&amp;(void) const { return mValue; } private: value_type mValue; }; </code></pre> <p>Now you've got a nice utility, and can just do:</p> <pre><code>typedef ranged_value&lt;unsigned char, 0, 15&gt; channel; void foo(const channel&amp; pChannel); </code></pre> <p>And it's re-usable in other scenarios. Just stick it all in a <code>"checked_ranges.hpp"</code> file and use it whenever you need. It's never bad to make abstractions, and having utilities around isn't harmful.</p> <p>Also, never worry about overhead. Creating a class simply consists of running the same code you would do anyway. Additionally, clean code is to be preferred over anything else; performance is a last concern. Once you're done, then you can get a profiler to measure (not guess) where the slow parts are.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload