Search code examples
c++parenthesescurly-braces

Initialize struct using parentheses instead of curly braces and an equal sign


How can I initialize struct using parentheses instead of curly braces and an equal sign?

Matrix2x2 m1 = {1, 2, 3, 4};
Matrix2x2 res(5*m1);

Here, for example, the first struct is initialized by using the curly braces and an equal sign, while the second is initializing as I understand by copying values from the multiplication result.

I would like m1 to be initialized with the help of parentheses somehow. Is it possible?

#pragma once

#include <iostream>

struct Matrix2x2
{
    double _00, _01, 
        _10, _11;
};

std::istream& operator>>(std::istream&, Matrix2x2&);
std::ostream& operator<<(std::ostream&, Matrix2x2&);
Matrix2x2 operator*(const double&, const Matrix2x2&);


#include "Matrix.h"

std::istream& operator>>(std::istream& is, Matrix2x2& m)
{
    return is >> m._00 >> m._01 >> m._10 >> m._11;
}

std::ostream& operator<<(std::ostream& os, Matrix2x2& m)
{
    return os << m._00 << ' ' << m._01 << std::endl 
        << m._10 << ' ' << m._11 << std::endl;
}

Matrix2x2 operator*(const double& c, const Matrix2x2& m)
{
    Matrix2x2 res = {c*m._00, c*m._01, c*m._10, c*m._11};
    return res;
}

Solution

  • You can have a user-defined constructor for your struct:

    #include <iostream>
    struct Matrix2x2 {
        int x1;
        int x2;
        int x3;
        int x4;
    
        Matrix2x2(int a, int b, int c, int d)
            : x1(a), x2(b), x3(c), x4(d)
        {}
    };
    
    int main() {
        Matrix2x2 m1 = { 1, 2, 3, 4 }; // list initialization
        Matrix2x2 res(1, 2, 3, 4); // calls user-defined constructor
    }
    

    And pass in the arguments when creating an object (surrounded by parentheses). But you should really prefer the braced initializer instead as it is immune to the most vexing parse:

    Matrix2x2 res{ 1, 2, 3, 4 }; // calls user-defined constructor, braced initialization