overloading << to accept any primitive type

I have a class where I need to overload the << operator. However, when compiling, I get an error stating there is not match for the << operator.

The line producing the error is
cls << "string";

Now, I know I did not overload it properly. I need it to be able to accept fundamental type of data (string, int, float...).

In my header I have

SO& operator<<(std::ostream*);

and I also tried without the std::, still same error, also saying
" candidates are: SO& SO::operator<<(std::ostream*) "

and that is what I tried already...

I am a litttle bit unclear about what you're wanting to do. But if you want to insert a string, etc into your class then it's this kind of thing.

Depending on what your class does with the inserted data, you might be able to use a templated function. Otherwise you'll need to overload operator<< for each type separately.

Andy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// test.cpp

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class SO
{
public:
    SO& operator<<(const std::string& str);
    SO& operator<<(int val);
    template<typename TElem>
    SO& operator<<(const vector<TElem>& val);
};

SO& SO::operator<<(const std::string& str)
{
    cout << "SO : " << str << endl;
    return *this;
}
	
SO& SO::operator<<(int val)
{
    cout << "SO : #" << val << endl;
    return *this;
}

template<typename TElem>
SO& SO::operator<<(const vector<TElem>& val)
{
    const int cnt = val.size();
    for(int idx = 0; idx < cnt; ++idx)
    {
        *this << val[idx];
    }
    return *this;
}

int main()
{
    vector<int> ints;
    ints.push_back(2);
    ints.push_back(4);
    ints.push_back(6);
	
    vector<string> strs;
    strs.push_back("hello");
    strs.push_back("cplusplus");

    SO so;

    so << "what?";
    so << 123;
    so << ints;
    so << strs;

    return 0;
}  


SO : what?
SO : #123
SO : #2
SO : #4
SO : #6
SO : hello
SO : cplusplus

Last edited on
I guess I wanted to do something in the wrong way. The class is supposed to accept data (string, int...) and count the number of chars that pass thru it, meaning every char and every digit as part of an int, float, and the decimal dot. What I was thinking was to overload the << only once, so that whatever it accepts, it prints out and adds the number of chars, and in the end it prints the total number of chars. It seems that I have to overload the << for each var type.

Now, that brings me to a new problem - I need to cascade call the operator. So:

so<< "what ?" << 12 << 12.5;

In this example I have 3 << operators, each overloaded differently. Will I be able to cascade them?

EDIT:
I see you edited so, I used this example, and i did
so << "what" << 123;
and it works, thanks a lot!
Last edited on
Topic archived. No new replies allowed.