Error 'can not bind' std :: ostream 'when deploying a template in C ++

1

WHEN modifying a TAD with templates to make it generic (add templates):

For data entry / exit I have this code:

std::ostream& operator<<(std::ostream& os, Matriz & m)
{
  os << m.filas() << " " << m.columnas() << std::endl;
  os << std::setprecision(4) << std::fixed;
  for(int i=1; i <= m.filas(); i++)
  {
    for(int j=1; j <= m.columnas(); j++)
    {
      os << m.valor(i,j) << " ";
    }
    os << std::endl;
  }

  return os;
}

std::istream& operator>>(std::istream& is, Matriz& m)
{
  int filas, columnas;
  float v;

  is >> filas >> columnas;
  for (int i=1; i<=filas; i++)
  {
    for (int j=1; j<=columnas; j++)
    {
      is >> v;
      m.asignar(i,j,v);
    }
  }

  return is;
}

The definition (summarized):

#ifndef MATRIZ_HPP
#define MATRIZ_HPP

#include <stdexcept>
#include <iostream>
#include <iomanip>

template<typename E, int F, int C>
class Matriz
{
public:
  Matriz();
private:
  E elementos_[F][C];
};
#include "matriz.cpp"
#include "matriz_io.cpp"

#endif // MATRIZ_HPP

Implementation (summarized):

#include <limits>
#include <cmath>

template<typename E, int F, int C>
Matriz<E,F,C>::Matriz()
{
  for(int i=0; i<F; i++)
  {
    for(int j=0; j<C; j++)
    {
      elementos_[i][j] = 0; // Valor int, C++ lo convierte automáticamente a E.
    }
  }
}

Here jumps error:

#include "matriz.hpp"

#define Elemento float

#define MatrizPrueba Matriz<Elemento, 3, 3>

void probarCrearMatriz()
{
  MatrizPrueba m;
  std::cout << m;
}

This error:

  

error: can not bind 'std :: ostream {aka std :: basic_ostream}'   lvalue to 'std :: basic_ostream & &' std :: cout < < m;

Any idea why it occurs?

PS: if I remove the template the code is perfect.

    
asked by AguaSal 25.06.2017 в 00:32
source

1 answer

1

Well here I leave the code that I managed to solve, I have another question where I show all the files in case someone wants to see them.

Here is the solution to the code, we must put templates also in the overloading of matriz_io.cpp

 template<typename E, int filas, int columnas>
 std::ostream& operator<<(std::ostream& os, Matriz<E,filas,columnas>& m)
 {
   os << m.filas() << " " << m.columnas() << std::endl;
   os << std::setprecision(4) << std::fixed;
   for(int i=1; i <= m.filas(); i++)
   {
     for(int j=1; j <= m.columnas(); j++)
     {
       os << m.valor(i,j) << " ";
     }
     os << std::endl;
   }

   return os;
 }
 template<typename E, int F, int C>
 std::istream& operator>>(std::istream& is, Matriz<E,F,C>& m)
 {
     int filas, columnas;

   E v;

   is >> filas >> columnas;
   for (int i=1; i<=filas; i++)
   {
     for (int j=1; j<=columnas; j++)
     {
       is >> v;
       m.asignar(i,j,v);
     }
   }

   return is;
 }
    
answered by 25.06.2017 / 19:10
source