Not Suitable User Defined Conversion error with use of templates

2

I'm doing a program in C ++ that overload the operators. For example, for the operator * you would like it to be multiplied:

Cuadrado a(2.1);
Circulo b(1.3);
Circulo b(4.3);
Triangulo x= a * b * c

I have created the operation Cuadrado*Circulo but when assigning the result to the variable x that is of the triangle type, it indicates the following:

No Suitable User Defined Conversión from Cuadrado to Triangulo.

How can I convert a square type to a triangle?

template < int DIM1, int DIM2>
class Forma
{
    double value;
    public:

    int a;
    int b;

    Forma(double in) : value(in) {
        a = DIM1, b = DIM2;
    }

    //Getters
    const double get_data() const { return value; }

    //Setters
    const void set_data(double d)  {value=d; }
};

//Multiplication
template<class Cuadrado, class Circulo>
Circulo operator*(Cuadrado left, Circulo right)
{
Circulo result (left.get_data() * right.get_data());
return result;
}

using Cuadrado = Forma < 1, 1 >; 
using Triangulo = Forma < 1, 2 > ;
using Circulo = Forma < 1, 3 > ;

These types are created from the template of the class Forma .

    
asked by adamista 28.05.2018 в 12:45
source

1 answer

3

The error is not occurring in the multiplication but in the assignment:

Triangulo x = a * b * c:
//          ^

And the reason is this:

template<class Cuadrado, class Circulo>
Circulo operator*(Cuadrado left, Circulo right)

The multiplication operator returns an object of the same type as the second argument, then in the multiplication we have:

Triangulo = Cuadrado * Circulo * Circulo
Triangulo = Circulo * Circulo
Triangulo = Circulo

You need to overload the copy constructor ... but of course, it is not a copy constructor because it is not the same%% of Circle% ':

template < int DIM1, int DIM2>
class Forma
{
public:

  template<int DIM3, int DIM4>
  Forma( Forma<DIM3,DIM4> const& otro)
    : Forma{otro.get_data()}
  { }
};

Call the constructors in a nested way ( delegated constructors ) is only possible to start of C ++ 11

On the other hand, note that all members and operators of Triangulo are private ... then you will hardly get the code to compile. I understand that your design should look more like this:

template < int DIM1, int DIM2>
class Forma
{
    double value;
    public:

    int a;
    int b;

public:

    Forma(double in) : value(in) {
        a = DIM1, b = DIM2;
    }
    //Getters
    const double get_data() const { return value; }

    //Setters
    const void set_data(double d)  {value=d; }

  template<int DIM3, int DIM4>
  Forma( Forma<DIM3,DIM4> const& otro)
    : Forma(otro.get_data())
  { }

  template<int DIM3, int DIM4>
  Forma const& operator=(Forma<DIM3,DIM4> const& otro)
  {
    set_data(otro.get_data());
    return *this;
  }
};

I've taken the trouble to also include the assignment operator.

    
answered by 28.05.2018 / 13:00
source