Home > OS >  C Templates for classes
C Templates for classes

Time:11-11

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;
}

CodePudding user response:

compl is a c keyword (as an alternative for unary operator ~). 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 = ....

CodePudding user response:

Your have 3 errors in your program.

First instead of using the keyword compl you could use some other name like i did here.

Second, you were missing a ; after a statement return temp which is fixed in the above code link.

Third you were using

this._re = rhs._re;
this._im = rhs._im;

while the correct way to write this would be:

_re = rhs._re;//note the removed this.
_im = rhs._im;//note the removed this.

After correcting these errors the program works as can be seen here.

  • Related