Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6382725
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:33:36+00:00 2026-05-25T02:33:36+00:00

I’m teaching myself c++ by creating my own data structure class (a matrix, to

  • 0

I’m teaching myself c++ by creating my own data structure class (a matrix, to be exact) and I’ve changed it to a template class of type <T> from only using doubles. The overloaded matrix operators were pretty standard

    // A snippet of code from when this matrix wasn't a template class
    // Assignment
    Matrix& operator=( const Matrix& other );

    // Compound assignment
    Matrix& operator+=( const Matrix& other ); // matrix addition
    Matrix& operator-=( const Matrix& other ); // matrix subtracton
    Matrix& operator&=( const Matrix& other ); // elem by elem product
    Matrix& operator*=( const Matrix& other ); // matrix product

    // Binary, defined in terms of compound
    Matrix& operator+( const Matrix& other ) const; // matrix addition
    Matrix& operator-( const Matrix& other ) const; // matrix subtracton
    Matrix& operator&( const Matrix& other ) const; // elem by elem product
    Matrix& operator*( const Matrix& other ) const; // matrix product

    // examples of += and +, others similar
    Matrix& Matrix::operator+=( const Matrix& rhs )
    {
        for( unsigned int i = 0; i < getCols()*getRows(); i++ )
        {
            this->elements.at(i) += rhs.elements.at(i);
        }
        return *this;
    }

    Matrix& Matrix::operator+( const Matrix& rhs ) const
    {
        return Matrix(*this) += rhs;
    }

But now that Matrix can have a type, I’m having trouble determining which of the matrix references should be type <T> and what the consequences would be. Should I allow dissimilar types operate on each other (eg., Matrix<foo> a + Matrix<bar> b is valid)? I’m also a little fuzzy on how

One reason I’m interested in dissimilar types is to facilitate the use of complex numbers in the future. I’m a newbie at c++ but am happy to dive in over my head to learn. If you’re familiar with any free online resources that deal with this problem I would find that most helpful.

Edit: no wonder no one thought this made sense all of my angle brackets in the body were treated as tags! I can’t figure out how to escape them, so I’ll inline code them.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:33:37+00:00Added an answer on May 25, 2026 at 2:33 am

    I figure that I should illustrate my comment about parameterizing matrix dimensions, since you might not have seen this technique before.

    template<class T, size_t NRows, size_t NCols>
    class Matrix
    {public:
        Matrix() {} // `data` gets its default constructor, which for simple types
                    // like `float` means uninitialized, just like C.
        Matrix(const T& initialValue)
        {   // extra braces omitted for brevity.
            for(size_t i = 0; i < NRows; ++i)
                for(size_t j = 0; j < NCols; ++j)
                    data[i][j] = initialValue;
        }
        template<class U>
        Matrix(const Matrix<U, NRows, NCols>& original)
        {
            for(size_t i = 0; i < NRows; ++i)
                for(size_t j = 0; j < NCols; ++j)
                    data[i][j] = T(original.data[i][j]);
        }
    
    private:
        T data[NRows][NCols];
    
    public:
        // Matrix copy -- ONLY valid if dimensions match, else compile error.
        template<class U>
        const Matrix<T, NRows, NCols>& (const Matrix<U, NRows, NCols>& original)
        {
            for(size_t i = 0; i < NRows; ++i)
                for(size_t j = 0; j < NCols; ++j)
                    data[i][j] = T(original.data[i][j]);
            return *this;
        }
    
        // Feel the magic: Matrix multiply only compiles if all dimensions
        // are correct.
        template<class U, size_t NOutCols>
        Matrix<T, NRows, NOutCols> Matrix::operator*(
            const Matrix<T, NCols, NOutCols>& rhs ) const
        {
            Matrix<T, NRows, NOutCols> result;
            for(size_t i = 0; i < NRows; ++i)
                for(size_t j = 0; j < NOutCols; ++j)
                {
                    T x = data[i][0] * T(original.data[0][j]);
                    for(size_t k = 1; k < NCols; ++k)
                        x += data[i][k] * T(original.data[k][j]);
                    result[i][j] = x;
                }
            return result;
        }
    
    };
    

    So you’d declare a 2×4 matrix of floats, initialized to 1.0, as:

    Matrix<float, 2, 4> testArray(1.0);
    

    Note that there is no requirement for the storage to be on the heap (i.e. using operator new) since the size is fixed. You could allocate this on the stack.

    You can create another couple matrices of ints:

    Matrix<int, 2, 4> testArrayIntA(2);
    Matrix<int, 4, 2> testArrayIntB(100);
    

    For copying, dimensions must match though types do not:

    Matrix<float, 2, 4> testArray2(testArrayIntA); // works
    Matrix<float, 2, 4> testArray3(testArrayIntB); // compile error
    // No implementation for mismatched dimensions.
    
    testArray = testArrayIntA; // works
    testArray = testArrayIntB; // compile error, same reason
    

    Multiplication must have the right dimensions:

    Matrix<float, 2, 2> testArrayMult(testArray * testArrayIntB); // works
    Matrix<float, 4, 4> testArrayMult2(testArray * testArrayIntB); // compile error
    Matrix<float, 4, 4> testArrayMult2(testArrayIntB * testArray); // works
    

    Note that, if there’s a botch, it is caught at compile time. This is only possible if the matrix dimensions are fixed at compile time, though. Also note that this bounds checking results in no additional runtime code. It’s the same code that you’d get if you just made the dimensions constant.

    Resizing

    If you don’t know your matrix dimensions at compile time, but must wait until runtime, this code may not be of much use. You’ll have to write a class that internally stores the dimensions and a pointer to the actual data, and it will need to do everything at runtime. Hint: write your operator [] to treat the matrix as a reshaped 1xN or Nx1 vector, and use operator () to perform multiple-index accesses. This is because operator [] can only take one parameter, but operator () has no such limit. It’s easy to shoot yourself in the foot (force the optimizer to give up, at least) by trying to support a M[x][y] syntax.

    That said, if there’s some kind of standard matrix resizing that you do to resize one Matrix into another, given that all dimensions are known at compile time, then you could write a function to do the resize. For example, this template function will reshape any Matrix into a column vector:

    template<class T, size_t NRows, size_t NCols>
    Matrix<T, NRows * NCols, 1> column_vector(const Matrix<T, NRows, NCols>& original)
    {   Matrix<T, NRows * NCols, 1> result;
    
        for(size_t i = 0; i < NRows; ++i)
            for(size_t j = 0; j < NCols; ++j)
                result.data[i * NCols + j][0] = original.data[i][j];
    
        // Or use the following if you want to be sure things are really optimized.
        /*for(size_t i = 0; i < NRows * NCols; ++i)
            static_cast<T*>(result.data)[i] = static_cast<T*>(original.data)[i];
        */
        // (It could be reinterpret_cast instead of static_cast. I haven't tested
        // this. Note that the optimizer may be smart enough to generate the same
        // code for both versions. Test yours to be sure; if they generate the
        // same code, prefer the more legible earlier version.)
    
        return result;
    }
    

    … well, I think that’s a column vector, anyway. Hope it’s obvious how to fix it if not. Anyway, the optimizer will see that you’re returning result and remove the extra copy operations, basically constructing the result right where the caller wants to see it.

    Compile-Time Dimension Sanity Check

    Say we want the compiler to stop if a dimension is 0 (normally resulting in an empty Matrix). There’s a trick I’ve heard called “Compile-Time Assertion” which uses template specialization and is declared as:

    template<bool Test> struct compiler_assert;
    template<> struct compiler_assert<true> {};
    

    What this does is let you write code such as:

    private:
        static const compiler_assert<(NRows > 0)> test_row_count;
        static const compiler_assert<(NCols > 0)> test_col_count;
    

    The basic idea is that, if the condition is true, the template turns into an empty struct that nobody uses and gets silently discarded. But if it’s false, the compiler can’t find a definition for struct compiler_assert<false> (just a declaration, which isn’t enough) and errors out.

    Better is Andrei Alexandrescu’s version (from his book), which lets you use the declared name of the assertion object as an impromptu error message:

    template<bool> struct CompileTimeChecker
    { CompileTimeChecker(...); };
    template<> struct CompileTimeChecker<false> {};
    #define STATIC_CHECK(expr, msg) { class ERROR_##msg {}; \
        (void)sizeof(CompileTimeChecker<(expr)>(ERROR_##msg())); }
    

    What you fill in for msg has to be a valid identifier (letters, numbers, and underscores only), but that’s no big deal. Then we just replace the default constructor with:

    Matrix()
    {   // `data` gets its default constructor, which for simple types
        // like `float` means uninitialized, just like C.
        STATIC_CHECK(NRows > 0, NRows_Is_Zero);
        STATIC_CHECK(NCols > 0, NCols_Is_Zero);
    }
    

    And voila, the compiler stops if we mistakenly set one of the dimensions to 0. For how it works, see page 25 of Andrei’s book. Note that in the true case, the generated code gets discarded so long as the test has no side effects, so there’s no bloat.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I want use html5's new tag to play a wav file (currently only supported
I am currently running into a problem where an element is coming back from
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I want to construct a data frame in an Rcpp function, but when I
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.