Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Can I overload operator<< using a template?

Reply
Thread Tools

Can I overload operator<< using a template?

 
 
fungus
Guest
Posts: n/a
 
      01-06-2007
Jacek Dziedzic wrote:
> fungus wrote:
>> Why can't the compiler write operator==
>> and operator< for me automatically?

>
> // how does the compiler know whether to
> // compare by employee_name or by date_hired?
>


If I want specifics like these then I'll write
appropriate code but I can think of many
situations where all I want is generic compares
and fast lookups (eg. std::map, std::lower_bound).


--
<\___/>
/ O O \
\_____/ FTB. For email, remove my socks.


Were judging how a candidate will handle a nuclear
crisis by how well his staff creates campaign ads.
Its a completely nonsensical process.
 
Reply With Quote
 
 
 
 
fungus
Guest
Posts: n/a
 
      01-06-2007
fungus wrote:
> Rolf Magnus wrote:
>> That should work. Your code is a bit short, so it's
>> hard to tell why it wouldn't.

>
> I'll have another play with it and see what happens...
>


I figured it out - it's all to do with namespaces.

Here's a "broken" piece of code:

#include <iostream>
#include <string>

namespace foo {
class A {
public:
void writeTo(std:stream& os) const {
os << "A";
}
};
void operator<<(std:stream& os, const class B&);
void test();
}

template<typename T, typename S>
S& operator<<(S& d, const T& t)
{
t.writeTo(d);
return d;
}

void foo::test()
{
A a;
std::cout << a << '\n';
}

int main(int argc,char **argv)
{
foo::test();
}


The operator<< in namespace foo is hiding the template
operator<< (which is in the global namespace).


--
<\___/>
/ O O \
\_____/ FTB. For email, remove my socks.


Were judging how a candidate will handle a nuclear
crisis by how well his staff creates campaign ads.
Its a completely nonsensical process.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How can we overload '=' operator using friend function c++ Mahain C++ 3 12-20-2007 06:29 PM
BC30518: Overload resolution failed because no accessible 'ToString' can be called with these arguments: bcobra@gmail.com ASP .Net 0 05-24-2006 09:37 AM
Can I overload throw or return? Atlas C++ 6 12-28-2004 07:43 PM
function overload (not operator overload) Ying-Chieh Liao Perl Misc 3 10-11-2004 11:24 AM
How use the overload of>> (or<<) of a class in the overload of << and >> of another class? Piotre Ugrumov C++ 3 01-25-2004 08:08 PM



Advertisments