Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make my matrix object implicitly convert to scalar when its dimensions are 1x1?
    text
    copied!<p>I have written a <code>Matrix</code> class. It does multiplications between matrices. Sometimes multiplication of matrices yield a 1x1 matrix (e.g.; inner product of two column vectors). Is it possible to make a <code>Matrix</code> object directly return a scalar value when it is one-by-one?</p> <pre><code>template &lt;class T&gt; class Matrix { public: // ... T&amp; operator()(uint64_t unRow, uint64_t unCol = 0) throw(MatrixOutOfRange); const T&amp; operator()(uint64_t unRow, uint64_t unCol = 0) const throw(MatrixOutOfRange); // ... protected: std::vector&lt;T&gt; MatrixArray; // ... }; // ... template &lt;class T&gt; T &amp; Matrix&lt;T&gt;::operator()(uint64_t unRow, uint64_t unCol /*= 0*/) throw(MatrixOutOfRange) { /* Bound checking here */ return MatrixArray[m_unColSize * unRow + unCol]; } template &lt;class T&gt; const T &amp; Matrix&lt;T&gt;::operator()(uint64_t unRow, uint64_t unCol /*= 0*/) const throw(MatrixOutOfRange) { /* Bound checking here */ return MatrixArray[m_unColSize * unRow + unCol]; } // ... </code></pre> <hr> <p>Example code:</p> <p><img src="https://i.stack.imgur.com/ziirN.png" alt="Latex image"></p> <pre><code>Matrix&lt;double&gt; A (3, 1, 1.0, 2.0, 3.0); Matrix&lt;double&gt; AT(1, 3, 1.0, 2.0, 3.0); // Transpose of the A matrix Matrix&lt;double&gt; B (3, 1, 4.0, 5.0, 6.0); Matrix&lt;double&gt; C(); C = AT * B; double Result1 = C(0, 0); double Result2 = (AT * B)(0, 0); double Result3 = A.InnerProductWith(B)(0, 0); </code></pre> <p>I want to drop the unnecessary element location specifier arguments <code>(0, 0)</code> when the result is a one-by-one matrix. Like this:</p> <pre><code>C = AT * B; double Result1 = C; double Result2 = AT * B; double Result3 = A.InnerProductWith(B); </code></pre> <p>It is OK if it throws an exception if the result is not one-by-one.</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