[EDIT] I am writing a template class with type argument T
. In one of the functions member of that class, a variable with type T
is expected to be written to a std::ofstream
object. Everything is fine until I instantiate this class with a custom type argument Fraction
. The error occurs although I did overload the operator <<
.
// collection.h
#include <fstream>
template<typename T>
class Collection
{
public:
void writeToFile();
private:
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;
}
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>
(ie the declaraction of operator<<
is above it).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.