I have written a code:
#include <iostream>
#include <cassert>
using namespace std;
template<typename T>
class dynArray{
int size;
T* ptr;
public:
dynArray(int n=0);
~dynArray();
T& operator[] (const int index);
friend ostream& operator<<<T>(ostream& os,const dynArray<T>& A);
};
template<typename T> dynArray<T>::dynArray(int n):size(n){
if (size==0)
{
cout << "Size Zero"<< endl;
ptr=NULL;}
else
{
try{
ptr = new T[size];
cout << "Constructor Called" << endl;
}
catch(bad_alloc xa)
{
cout << "Allocation Failure" <<endl;
exit(EXIT_FAILURE);
}
}
}
template<typename T> dynArray<T>::~dynArray(){
cout << "Destructor Called for array of size : " << size << endl;
delete[] ptr;
}
template<typename T> T& dynArray<T>::operator[] (const int index){
assert(index >=0 && index <size);
return *(ptr+index);
}
template<typename T> ostream& operator<< <T>(ostream& os,const dynArray<T>& A){
for (int i=0; i < A.size ; i++)
os << *(A.ptr+i) << " ";
return os;
}
int main()
{
dynArray<int> array1;
dynArray<int> array2(5);
array2[0]=15;
array2[3]= 45;
cout << array2 << endl;
return 0;
}
But while compiling getting error:
$ g++ -Wall DynArray.cpp -o DynArray
DynArray.cpp:46: error: partial specialization `operator<< <T>' of function template
DynArray.cpp: In instantiation of `dynArray<int>':
DynArray.cpp:54: instantiated from here
DynArray.cpp:14: error: template-id `operator<< <int>' for `std::basic_ostream<char, std::char_traits<char> >& operator<<(std::basic_ostream<char, std::char_traits<char> >&, const dynArray<int>&)' does not match any template declaration
DynArray.cpp: In function `std::ostream& operator<<(std::ostream&, const dynArray<T>&) [with T = int]':
DynArray.cpp:61: instantiated from here
DynArray.cpp:8: error: `int dynArray<int>::size' is private
DynArray.cpp:47: error: within this context
DynArray.cpp:9: error: `int*dynArray<int>::ptr' is private
DynArray.cpp:48: error: within this context
I think my template syntax is wrong for operator<<. Can any one help please? Not able to figure out where is the mistake.
You cannot friend a specialization of an undeclared template function. You need to declare the operator << beforehand. Of course to do so, you'll need to already have a declaration of dynArray. This mess of forward declarations looks like this (Live at Coliru):
template<typename T> class dynArray;
template<typename T>
ostream& operator << (ostream& os, const dynArray<T>& A);
template<typename T>
class dynArray {
// ...
friend ostream& operator<< <T>(ostream& os, const dynArray& A);
};
As #ooga points out in his comment, the template parameters in the friend declaration are unnecessary; the compiler can deduce them. You could simply declare it as:
friend ostream& operator<< <> (ostream& os, const dynArray& A);
I personally find that syntax a bit punctuation-heavy in this instance.
Alternatively, if you find the forward declarations offensive, you could declare a separate non-template friend function for each specialization of dynArray by defining it in the class definition (Coliru again):
template<typename T>
class dynArray {
// ...
friend ostream& operator<< (ostream& os,const dynArray& A) {
for (int i=0; i < A.size ; i++)
os << *(A.ptr+i) << " ";
return os;
}
};
In the class declare friend as :-
template<typename U>
friend ostream& operator<<(ostream& os,const dynArray<U>& A);
And define it as :-
template<typename U>
ostream& operator<< (ostream& os,const dynArray<U>& A){...}
See HERE
Related
Here's the functionality I am expecting to achieve:
darray<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
std::cout << a << std::endl; // displays: {1, 2, 3}
My implementation:
template <typename T>
class darray
{
private:
long m_capacity;
long m_size;
T* m_data;
void resize();
public:
// constructors & destructors
darray();
// operations
void push_back(T);
std::ostream& print(std::ostream&) const;
template<typename U> friend std::ostream& operator<<(std::ostream& os, U const& ar);
};
template<typename T>
std::ostream& darray<T>::print(std::ostream& os) const
{
os << "{ ";
for (size_t i = 0; i < m_size; i++)
{
os << m_data[i] << ", ";
if ( i == m_size - 1 )
os << m_data[i];
}
os << " }\n";
return arr;
}
template<typename U>
std::ostream& operator<<(std::ostream& os, U const& obj)
{
return obj.print(os);
}
produces an error:
error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const char [66]’)
But, when I change the parameter of operator<< to accept a darray<U> instead , it works fine:
template<typename U>
std::ostream& operator<<(std::ostream& os, darray<U> const& obj)
{
return obj.print(os);
}
What am I missing here?
Update:
I also tried doing this, changing the parameter to darray<U> type in the definition and the implementation, but it still produces the same error:
template <typename T>
class darray
{
private:
long m_capacity;
long m_size;
T* m_data;
void resize();
public:
// constructors & destructors
darray();
// operations
void push_back(T);
std::ostream& print(std::ostream&) const;
template<typename U> friend std::ostream& operator<<(std::ostream& os, darray<U> const& ar);
};
template<typename T>
std::ostream& darray<T>::print(std::ostream& os) const
{
os << "{ ";
for (size_t i = 0; i < m_size; i++)
{
os << m_data[i] << ", ";
if ( i == m_size - 1 )
os << m_data[i];
}
os << " }\n";
return os;
}
template<typename U>
std::ostream& operator<<(std::ostream& os, darray<U> const& obj)
{
return obj.print(os);
}
Friend functions in template classes have to be defined inside the class declaration. This is the only way I have found to have the friend function to correctly accept an instance of the templated class with the expected template.
So here I would write:
...
friend std::ostream& operator<<(std::ostream& os, darray<T> const& ar) {
ar.print(os);
return os;
}
...
But beware: your class contains a raw pointer to allocated memory which is probably deleted in the class destructor. Per the rule of five, you must explicitely declare (or delete) the copy/move constructors and assignment operators.
In your darray<T>::print function, if you change
os << m_data[i] << ", ";
to
os << m_data[i];
os << ", ";
then the compiler doesn't complain and it works fine. I don't know why.
I am reading Section 2.4 of the book "C++ tempalte, a complete guide".
I tried to override output operator (<<) as a function template outside the class template Stack<>.
Below is my code, but it doesn't work.
#include <iostream>
#include <string>
#include <vector>
template<class T>
class Stack
{
private:
std::vector<T> v;
public:
void push(T a);
void printOn(std::ostream & os) const;
template <typename U>
friend std::ostream& operator<< (std::ostream& out, const Stack<U> & s);
};
template<typename T>
std::ostream& operator<< (std::ostream out, const Stack<T> & s)
{
s.printOn(out);
return out;
}
template<class T>
void Stack<T>::push(T a)
{
v.push_back(a);
}
template<class T>
void Stack<T>::printOn(std::ostream & out) const
{
for(T const & vi : v)
{out << vi << " ";}
}
int main()
{
Stack<int> s1;
s1.push(12);
s1.push(34);
std::cout << s1;
}
You are just omitting the &, which makes the operator<< inside and outside the class have different function signatures, they are both valid for std::cout << s1, hence the ambiguity
template<typename T>
std::ostream& operator<< (std::ostream& out, const Stack<T> & s)
// ^
{
s.printOn(out);
return out;
}
Trying to code a better version of array type i have run into an issue. For some reason the declaration doesnt work. It throws at me bunch of weird errors. Tried looking up the issue but havent found anything so far. Here is the code:
Template <class T>
class SafeArray {
private:
int size;
int elements;
int index;
T* arr;
public:
SafeArray(int n);
~SafeArray();
void push_back(T item);
void resize(int size);
friend std::ostream& operator << (std::ostream& os, const SafeArray<T>& ar)
};
And the implementation outside the class:
template<class T>
std::ostream& operator << <T> (std::ostream& os, const SafeArray<T> & arr) {
for (int i = 0; i < arr.elements; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return os;
}
If you want friend template, the friend declaration should be
template <class T>
class SafeArray {
...
template<class X>
friend std::ostream& operator << (std::ostream& os, const SafeArray<X>& ar);
};
the implementation should be
template<class T>
std::ostream& operator << (std::ostream& os, const SafeArray<T> & arr) {
...
}
LIVE
BTW: In the implementation of operator<<, I think std::cout << arr[i] << " "; should be std::cout << arr.arr[i] << " ";.
I've recently learned that there are two ways to declare a template friend class or function. For example, to declare a template friend class, you may do this
template <typename T>
class goo
{
template <typename T>
friend class foo;
};
or this
template <typename T>
class goo
{
friend class foo <T>;
};
These two declarations are in fact different. The former allows you to use any type of template friend class foo with any type of template friend class goo. Where as the latter only allows you to use the same type such that you may do foo<int> with goo<int> but not foo<int> with goo<char>.
In the header file below, I try to use the latter form of the declaration to make my template friend function friend std::ostream& operator<<(std::ostream&, const Array<T>&); more type-specific in an effort to make my program more encapsulated.
//ARRAY_H
#include <iostream>
#include "Animal.h"
const int DefaultSize = 3;
template <typename T> // declare the template and the paramenter
class Array // the class being parameterized
{
public:
Array(int itsSize = DefaultSize);
Array(const Array &rhs);
~Array() { delete[] pType; }
// operators
Array& operator=(const Array&);
T& operator[](int offSet) { return pType[offSet]; }
const T& operator[](int offSet) const { return pType[offSet]; }
// accessors
int GetSize() const { return itsSize; }
// friend function
friend std::ostream& operator<< <T>(std::ostream&, const Array<T>&);
private:
T *pType;
int itsSize;
};
template <typename T>
Array<T>::Array(int size = DefaultSize) :itsSize(size)
{
pType = new T[size];
for (int i = 0; i < size; i++)
pType[i] = static_cast<T>(0);
}
Array<Animal>::Array(int AnimalArraySize) :itsSize(AnimalArraySize)
{
pType = new Animal[AnimalArraySize];
}
template <typename T>
Array<T>::Array(const Array &rhs)
{
itsSize = rhs.GetSzie();
pType = new T[itsSize];
for (int i = 0; i < itsSize; i++)
pType[i] = rhs[i];
}
template <typename T>
Array<T>& Array<T>::operator=(const Array &rhs)
{
if (this == &rhs)
return *this;
delete[] pType;
itsSize = rhs.GetSize();
pType = new T[itsSize];
for (int i = 0; i < itsSize; i++)
pType[i] = rhs[i];
return *this;
}
template <typename T>
std::ostream& operator<<(std::ostream& output, const Array<T> &theArray)
{
for (int i = 0; i < theArray.GetSize(); i++)
output << "[" << i << "]" << theArray[i] << std::endl;
return output;
}
#endif
However, I receive a compiler error "error C2143: syntax error : missing ';' before '<'" for line 23 which is friend std::ostream& operator<< <T>(std::ostream&, const Array<T>&);.
When using the former form of the declaration by changing line 23 to this
template <typename T>
friend std::ostream& operator<<(std::ostream&, const Array<T>&);
My program executes without any errors.
I assume I cannot use the same syntax from type-specific template friend classes for type-specific template friend functions, or that I may be missing some kind of forward declaration. I've searched through stack-overflow and the closest topic I could find for this problem is here, but they only discuss type-specific template friend classes. I am unable to find a topic that discusses the correct syntax for using a template friend function in this way.
If this is a syntax error, what is the correct way to declare my type-specific template friend function? If this is not a syntax error, why will my program not compile?
Here are the rest of my project files for your reference. The desired behavior of my program is to show how a parametrized array uses a template to create multiple instances of different array types.
//ANIMAL_H
#ifndef ANIMAL_H
#define ANIMAL_H
#include <iostream>
class Animal
{
public:
// constructors
Animal();
Animal(int);
~Animal();
// accessors
int GetWeight() const { return itsWeight; }
void SetWeight(int theWeight) { itsWeight = theWeight; }
// friend operators
friend std::ostream& operator<<(std::ostream&, const Animal&);
private:
int itsWeight;
};
#endif
//ANIMAL.CPP
#include "Animal.h"
#include <iostream>
Animal::Animal() :itsWeight(0)
{
std::cout << "animal() ";
}
Animal::Animal(int weight) : itsWeight(weight)
{
std::cout << "animal(int) ";
}
Animal::~Animal()
{
std::cout << "Destroyed an animal...";
}
std::ostream& operator<<(std::ostream& theStream, const Animal& theAnimal)
{
theStream << theAnimal.GetWeight();
return theStream;
}
//MAIN.CPP
#include <iostream>
#include "Animal.h"
#include "Array.h"
void IntFillFunction(Array<int>& theArray);
void AnimalFillFunction(Array<Animal>& theArray);
int main()
{
Array<int> intArray;
Array<Animal> animalArray;
IntFillFunction(intArray);
AnimalFillFunction(animalArray);
std::cout << "intArray...\n" << intArray;
std::cout << "\nanimalArray...\n" << animalArray << std::endl;
std::cin.get();
return 0;
}
void IntFillFunction(Array<int>& theArray)
{
bool Stop = false;
int offset, value;
while (!Stop)
{
std::cout << "Enter an offset (0-9) and a value. ";
std::cout << "(-1 to stop): ";
std::cin >> offset >> value;
if (offset < 0)
break;
if (offset > 9)
{
std::cout << "***Please use values between 0 and 9.***\n";
continue;
}
theArray[offset] = value;
}
}
void AnimalFillFunction(Array<Animal>& theArray)
{
Animal *pAnimal;
for (int i = 0; i < theArray.GetSize(); i++)
{
pAnimal = new Animal(i * 10);
theArray[i] = *pAnimal;
delete pAnimal;
}
}
You need to declare the function template before you refer to a specialization as a friend.
// Forward declare class template.
template <typename T> class Array;
// Declare function template.
template <typename T>
std::ostream& operator<<(std::ostream& os, const Array<T>& arr);
template <typename T>
class Array
{
//...
friend std::ostream& operator<< <>(
std::ostream& os, const Array<T>& arr);
//...
};
You need a forward declaration of the function template (just as you need with a class template) in order to friend a specialization. Your code should be:
template <typename T>
std::ostream& operator<<(std::ostream& output, const Array<T> &theArray);
template <typename T>
class Animal
{
// ...
friend std::ostream& operator<< <T>(std::ostream&, const Array<T>&);
};
I am trying to overload operator<< in my code. If I comment out the lines where I try to use the << operator with my custom class, it compiles fine. The error almost looks like it doesn't like the c++ libraries (?).
All my research on this problem has stated that it is a linking problem. Most suggest using g++ instead of gcc. I am using g++ as my compiler, and I get this error still.
Code:
#include <iostream>
using namespace std;
//prototype the class and the functions
template<class T> class strange;
template<class T> ostream& operator<< (ostream& osObject, strange<T>& sObject);
//begin class
template <class T>
class strange
{
public:
// .... function prototypes go here.
strange(T x,T y);
friend ostream& operator<< <> (ostream& osObject, strange<T>& sObject);
private:
T a;
T b;
};
// .... your function definitions go here
template <class T>
strange<T>::strange(T first, T second){
a = first;
b = second;
}
template <class T>
ostream& operator<< (ostream& osObject, const strange<T>& sObject){
osObject << sObject.a << ", " << sObject.b;
return osObject;
}
int main()
{
strange<int> x1(4,6) , x2(12,2) ;
//strange<char> y1('m','n') , y2('m','n') ;
cout << "x1 = " << x1 << endl;
return 0;
}
Error:
test.cpp:(.text+0x7a): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, strange<int>&)'
collect2: ld returned 1 exit status
Any idea what is causing this?
I made two changes, one to the friend definition, and one to the prototype. This should compile:
#include <iostream>
using namespace std;
//prototype the class and the functions
template<class T> class strange;
template<class T> ostream& operator<< (ostream& osObject, const strange<T>& sObject);
//begin class
template <class T>
class strange
{
public:
// .... function prototypes go here.
strange(T x,T y);
friend ostream& operator<< <> (ostream& osObject, const strange<T>& sObject);
private:
T a;
T b;
};
// .... your function definitions go here
template <class T>
strange<T>::strange(T first, T second){
a = first;
b = second;
}
template <class T>
ostream& operator<< (ostream& osObject, const strange<T>& sObject){
osObject << sObject.a << ", " << sObject.b;
return osObject;
}
int main()
{
strange<int> x1(4,6) , x2(12,2) ;
//strange<char> y1('m','n') , y2('m','n') ;
cout << "x1 = " << x1 << endl;
return 0;
}
And this compiles in clang, g++ and at ideone
To explain the issue, the compiler is looking at link time for a definition for:
std::ostream & operator<< <int>(std::ostream &, strange<int>&);
When you only have a definition for:
std::ostream & operator<< <int>(std::ostream &, strange<int> const &);
This is because of the miscommunication between your prototypes (both the explicit one and the friend) and your definition.