Rickie Rickie - 1 year ago 84
C++ Question

Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)

I am writing a template class with type argument

. In one of the functions member of that class, a variable with type
is expected to be written to a
object. Everything is fine until I instantiate this class with a custom type argument
. The error occurs although I did overload the
operator <<

// collection.h
#include <fstream>
template<typename T>
class Collection
void writeToFile();
T val;

template<typename T>
inline void Collection<T>::writeToFile()
std::ofstream file("output.txt");
file << val;


// Fraction.cpp
#include <iostream>
std::ostream& operator << (std::ostream& str, const Fraction& f)
std::cout << "Hello";
return str;

Answer Source

New answer:

You answer need to declare operator << with a line like this in Fraction.h, and #include "Fraction.h" before the code that uses it:

std::ostream& operator << (std::ostream& str, const Fraction& f);

The concept of declarations vs definitions is fundamental to C++ (and C), so if you don't understand the distinction, search the web about it now to save yourself any more confusion.

Edit: Old answer:

Are you sure that you are really just doing file << arr[i] and not file << somethingElse << arr[i]? Because if you do the latter, then the static type of file << somethingElse is likely to be std::ostream& rather than std::ofstream&. In that case, the solution is to change operator<< (..., Fraction) to accept (and return) a general std::ostream& rather than std::ofstream&.

Edit: Another possibility: you need to make sure the declaration of operator<< (..., Fraction) is visible from the place you instantiate Collection<Fraction> (i.e. the declaraction of operator<< is above it).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download