Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Templates for classes

in this code I tried to make a template for my class, and also 2 template functions, one for standard types and one for my template class, but I wanted to see if I can make a template in a template to get a defined function (I don’t know if this was the right way to make it). Finally, after I run the code it gives me some weird errors, like syntax errors etc. Thx for help!

  #include <iostream>

template <typename T>
class Complex
{
    T _re, _im;

public:
    Complex(T re = 0, T im = 0) :_re{re}, _im{im} {};
    ~Complex() {}
    Complex<T>& operator=(const Complex<T>& compl) { if (this == &compl) return *this; this._re = compl._re; this._im = compl._im; return *this; }
    Complex<T> operator+(const Complex<T>& compl) { Complex<T> temp; temp._re = _re + compl._re; temp._im = _im + compl._im; return temp}
    friend std::ostream& operator<<(std::ostream& os, const Complex<T>& compl) { os << compl._re << " * i " << compl._im; return os; }
};

template <typename T>
T suma(T a, T b)
{
    return a + b;
}

template <template<typename> typename T, typename U>
void suma(T<U> a, T<U> b)
{
    T<U> temp;

    temp = a + b;

    std::cout << temp;
}

int main()
{
    int a1{ 1 }, b1{ 3 };
    std::cout << "Suma de int : " << suma<int>(a1, b1) << std::endl;

    double a2{ 2.1 }, b2{ 5.9 };
    std::cout << "Suma de double: " << suma<double>(a2, b2) << std::endl;

    Complex<int> c1(3, 5), c2(8, 9);
    std::cout << "Suma comple int: ";
    suma<Complex, int>(c1, c2);

    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

compl is a c++ keyword. You used compl as your operator overload parameters.

I didn’t know this just a few minutes ago. How did I find out? I pasted your code into godbolt.org and it highlighted the words "compl" as if they were keywords. One Internet search later, they are indeed keywords.

There’s also the use of this._re = ... and this._im = ... which doesn’t work since this is a pointer and not a reference, so it should be this->_re = ... or preferably, just _re = ....

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading