473,747 Members | 2,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem overriding >> and << in a template class

hello people i. can anybody help me, i dont know what is wrong with
this class. it has something to do with the me trying to override the
input output stream. if i dont override it, it works fine. i would
forget overriding it but i have to do it because its a coursework. here
is a simple version of the class
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
template <typename Item>
class Sample {
private:
vector<Item> results;

public:
Sample(vector<I tem> samps);

const vector<Item> get_data();

void set_data(const vector<Item> &v);

long double minimum();

long double maximum();

friend ostream& operator<<(ostr eam& os, const Sample& samp);

friend istream& operator>>(istr eam& is, Sample& samp);

};

template <typename item>
Sample<item>::S ample(vector<it em> samps) : results(samps) {}

template <typename item>
const vector<item> Sample<item>::g et_data(){
return results;
}

template <typename item>
void Sample<item>::s et_data(const vector<item> &v) {
results = v;
}

template <typename item>
long double Sample<item>::m inimum(){
long double m;
for(int i = 0; i < results.size(); i++){
if(i == 0){
m = results[i];
}else if(results[i] < m){
m = results[i];
}
}

return m;
}

template <typename item>
long double Sample<item>::m aximum(){
long double m;
for(int i = 0; i < results.size(); i++){
if(i == 0){
m = results[i];
}else if(results[i] > m){
m = results[i];
}
}

return m;
}

template <typename item>
ostream&
operator<<(ostr eam& os, const Sample<item>& samp){
cout << "<" << samp.results.si ze() << ":";

for(int i = 0; i < samp.results.si ze(); i++){
cout << " " << samp.results[i];
}

cout << " >";
return os;
}

template <typename item>
istream&
operator>>(istr eam& is, Sample<item>& samp){
string s;
int count = 0;
int size;
while (is >> s){
if(count == 0 && s[0] == '<' && s[s.size()-1] == ':'){
//size = parseInt(s.subs tr(0,s[s.size()-2]));
size = atoi((s.substr( 1,s.size()-2)).c_str());

cout << "begin size = " << size << endl;
}else if(s[s.size()-1] == '>'){
//size = parseInt(s.subs tr(0,s[s.size()-1]));
cout << "end " << endl;
count = 0;
break;
}else {
//size = parseInt(s.subs tr(0,s[s.size()-1]));
cout << count << " " << atof(s.c_str()) << endl;
samp.results.pu sh_back(atof(s. c_str()));
}
count++;
}
return is;
}

int main(){

vector<double> a;

a.push_back(7);
a.push_back(11) ;
a.push_back(2);
a.push_back(13) ;
a.push_back(3);
a.push_back(5);

//string s;
Sample<double> samp(a);
while (cin >> samp){

cout << samp.minimum() << endl << samp.maximum() << endl;

}

cout << samp;

return 0;
}
Any help will be greatly appreciated

Jul 23 '05 #1
2 2473
fr*******@hotma il.com wrote:
hello people i. can anybody help me,


Interestingly, this looks very much like an article I recently rejected
from comp.lang.c++.m oderated because it uses excessive code, i.e. it
includes loads of stuff entirely irrelevant to the question. Of course,
the rejection also mentioned the cause the of problem: The functions
you declare friends within the body of the class are non-template
functions and, except for the same name, entirely unrelated to the
function templates you use later!

For the friend functions to work correctly you need to declare them
*prior* to the class definition which in turn means that you also need
to forward declare the class definition itself. In addition, you need
to use a template argument list in the friend declaration. However,
since the template arguments can actually be deduced from the function
arguments, this template argument list can be empty. It just has to be
present to indicate that the function template is made a friend. The
whole code would look something like this:

#include <iostream>

template <typename> class foo;
template <typename T>
std::ostream& operator<< (std::ostream&, foo<T> const&);

template <typename T>
struct foo
{
foo(): val(17) {}
// ...
friend std::ostream& operator<< <>(std::ostream &, foo<T> const&);
private:
int val;
};

template<typena me T>
std::ostream& operator<< (std::ostream& os, foo<T> const& f)
{
return os << f.val;
}

int main()
{
std::cout << foo<int>() << "\n";
}

BTW, this is not "overriding " the output operator but "overloadin g".
There is signification difference between these two terms although
they look very similar. Overriding is the term used to indicate that
a virtual function of a base class is, well, overridden by a derived
class, i.e. it is the mechanism used to implement dynamic polymorphism.
The overridden function has essentially the same signature as the
original on (although the return type may be covariant; theoretically
the arguments could be contravariant but this is not supported by C++).
Overloading on the other means that the same function name is used for
an otherwise unrelated function: the signatures of overloaded functions
vary be definition and there is no dynamic polymorphism involved. Of
course, the unrelated functions should to similar things when they
share a common name but this is technically not required.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 23 '05 #2
thanks a lot for the help, i tried it and it worked. i really
appreciate it and God bless you.
franky

Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
3098
by: Philipp Lenssen | last post by:
My friend has the following problem (background: we want to transform XML to XHTML via XSLT): "We copy XHTML fragments into an output by using the following template: <xsl:template match="*" mode="xhtml"> <xsl:element name="{local-name()}"> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="xhtml"/> </xsl:element>
3
13154
by: TR | last post by:
Is it possible with CSS to prevent this wrapping alignment with a checkbox with a nested label? This is the label of the checkbox that wraps beneath it I'd prefer it looked like this, with a flush left margin:
4
2758
by: Grey Plastic | last post by:
I have several classes that all keep track of static data. However, the manner that they keep track of static data is identical, and so I'm using the template<class Child> class Parent { ... }; idiom (don't know the name of it, if there is one). The problem is that I don't want any of my classes to have public constructors. They should be created by a static member function. This is what I want to do, save for the fact that this...
2
11230
by: js | last post by:
I have a table rendered with XSLT. The first column has a radio button controls for user to make a selection for a particular row. All the values in the remaining columns are all concated with a &#xA0; (blank). I need to retieve the text in each cell of that row if the radio button on that row is clicked. Each <TD> has a numeric ID so that I can use it with document.getElementById().innerText method. I use Javascript to assign some...
3
3493
by: Jim in Arizona | last post by:
Most of the asp.net learning I've done has been from books that were written during the 1.0 framework. I didn't have a copy of visual studio when I started reading them then I got a hold of VS 2005 Beta 1, then Beta 2. I was using the <div runat="server"> statement on my projects. Once I placed a <div id="testdiv" runat="server"> within my aspx page, I could then manipulate it in the code behind like so: testdiv.visible = true...
4
5078
by: Gary li | last post by:
Hi, all I find "template template" class cann't been compiled in VC6 but can ok in Redhat9. I write a test program like as: template< template<class> class T> class A { }; int main() { return 0;
1
7297
by: sharmadeep1980 | last post by:
Hi All, I am facing a very unique problem while compling my project in "Release" build. The project is building in DEBUG mode but giving linking error on Release build. Here is the error: Creating library Release/fnimqcmd.lib and object Release/fnimqcmd.exp CoIMQCmd.obj : error LNK2001: unresolved external symbol
3
1904
by: Peterwkc | last post by:
Hello all expert C++ programmer, i fairly new to C++ programming. I have a class cellphone which contain dynamic pointer. I have create (example)ten cellphone. I want to ask user for the input and store in the list and finally sort the list according to the brand of cellphone. I learn C++ by myself. Therefore, i hope someone can guide me in this matter. I not asking for solution but guideline.
36
5103
by: Roedy Green | last post by:
The only browser I have encountered that supports <colgroup><col class="behold"></colgroup> to apply a CSS style to a whole column, is Microsoft Internet Explorer. I have been told it SHOULD NOT do so, since this is not part of the specification. How then to you apply styles to entire columns? Surely you don't have to write <td class="behold"on every row item.
0
8978
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8818
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9353
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9305
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9222
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6790
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6067
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4588
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.