Learning how templates and operator() work!

2 days ago by annieh to c/cpp

#include

template <typename T, const int length=5> class vector { public: T v[length]; vector operator +(const vector &obj) { vector tmp; for(int i = 0; i < length; i++) tmp.v[i] = v[i] + obj.v[i]; return tmp; /* This method below only works if length is a fixed size return {v[0] + obj.v[0], v[1] + obj.v[1], v[2] + obj.v[2], v[3] + obj.v[3], v[4] + obj.v[4]};*/ } }; int main() { vector a={1,2,3,4,5}; vector b={1,2,3,4,5};

auto c = a + b;

std::cout << "(int) ";
for(int i = 0; i < 5; i++)
    std::cout << c.v[i] << " ";
std::cout << std::endl;

}

tunetardis 2 points 2 days ago

Are you looking for a critique on the code, or tips on how you might improve it?

path: 0 26373760, hotness: undefined, score: 2, children: 0
tunetardis 2 points 2 days ago

I think you need to enclose your code block in triple back quotes to make it render properly in markdown. I've tried to fix it up a bit.

template <typename T, const int length=5> 
class vector {  
  public:  
    T v[length];  
    vector operator +(const vector &obj) {  
        vector tmp;  
        for(int i = 0; i < length; i++)  
            tmp.v[i] = v[i] + obj.v[i];  
        return tmp;  
        /* This method below only works if length is a fixed size return  
            {v[0] + obj.v[0], v[1] + obj.v[1], v[2] + obj.v[2], v[3] + obj.v[3], v[4] + obj.v[4]};*/ 
    } 
};  

int main() {  
    vector<int> a={1,2,3,4,5}; vector<int> b={1,2,3,4,5};  

    auto c = a + b;  

    std::cout << "(int) ";  
    for(int i = 0; i < 5; i++)  
        std::cout << c.v[i] << " ";  
    std::cout << std::endl;  
}  
path: 0 26373686, hotness: undefined, score: 2, children: 0
cpp
cpp

@programming.dev

login for more options
2381
416
45

The center for all discussion and news regarding C++.

Rules

  • Respect instance rules.
  • Don't be a jerk.
  • Please keep all posts related to C++.

go to feed...