Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Using operator of two intrinsic types as a function object
    text
    copied!<p>I have a vector-like class that contains an array of objects of type <code>"T"</code>, and I want to implement 4 arithmetic operators, which will apply the operation on each item:</p> <pre><code>// Constructors and other functions are omitted for brevity. template&lt;class T, unsigned int D&gt; class Vector { public: // Add a value to each item: naive implementation. void operator += (const T&amp;) { for (int i = 0; i &lt; D; ++i) { data[i] += value; } } void operator -= (const T&amp;) { ... } void operator *= (const T&amp;) { ... } void operator /= (const T&amp;) { ... } private: T items[D]; }; </code></pre> <p>Because operators will contain the same boilerplate code (looping over every element and applying appropriate operation), I thought I could generalize it:</p> <pre><code>template&lt;class T, unsigned int D&gt; class Vector { public: void operator += (const T&amp; value) { do_for_each(???, value); } void operator -= (const T&amp; value) { do_for_each(???, value); } void operator *= (const T&amp; value) { do_for_each(???, value); } void operator /= (const T&amp; value) { do_for_each(???, value); } private: void do_for_each(std::binary_function&lt;void, T, T&gt;&amp; op, T value) { std::for_each(data, data + D, std::bind2nd(op, value)); } T data[D]; }; </code></pre> <p>Now, the problem is, how do I pass an operator that takes two intrinsic types and returns <code>void</code> to <code>do_for_each</code>, as depicted in the example above? C++ does not let me do this trick for intrinsic types (<code>"T::operator+="</code> will not work if <code>"T"</code> is <code>"int"</code>).</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