473,670 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

operator<< for standard output and templates

Hi everyone,

I was unable to find out why my code is not compiling. I have a
template class and I'm trying to write the operator<< for standard
output. Does anyone know why this is not right? The code is as
follows...

// main class:
template <
class Individual,
class SelectionPolicy ,
template <classclass CrossOverPolicy = OnePointX,
class StoragePolicy = VectorPolicy<In dividual>
>
class Population : public SelectionPolicy , public
CrossOverPolicy <Individual{

// member variables and functions

// friend declaration for standard output
template <class I,class Se,template <classclass C,class St>
friend ostream& operator<<(ostr eam& os, Population<I,Se ,C,St>& pop);

};

// operator<< definition
template <class Individual,clas s SelectionPolicy ,template <class>
class CrossOverPolicy ,class StoragePolicy>
ostream& operator<<(ostr eam& os,
Population<Indi vidual,Selectio nPolicy,CrossOv erPolicy,Storag ePolicy>&
pop) {

os<<"pop"<<endl ;
return os;
}

// main function
int main(){

typedef Population<ind, t pop;
pop ccc(10);
cout<<ccc<<endl ;
return 0;
}

The compiler error message is:

main.cxx:104: error: ambiguous overload for 'operator<<' in 'std::cout
<< ccc'
gaPopulation.h: 411: note: candidates are: std::ostream&
operator<<(std: :ostream&, Population<I, Se, C, St>&) [with I =
Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, Se = TournamentSelec tor<2>, C =
OnePointX, St = VectorPolicy<In dividual<Chromo some<Objective< 1u,
Optimizator<min imize, BitSetPolicy, 2>, ClockMutator, Individual
= Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, SelectionPolicy =
TournamentSelec tor<2>, CrossOverPolicy = OnePointX, StoragePolicy =
VectorPolicy<In dividual<Chromo some<Objective< 1u, Optimizator<min imize>
>, BitSetPolicy, 2>, ClockMutator]
gaPopulation.h: 441: note: std::ostream&
operator<<(std: :ostream&, Population<Indi vidual, SelectionPolicy ,
CrossOverPolicy , StoragePolicy>& ) [with Individual =
Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, SelectionPolicy =
TournamentSelec tor<2>, CrossOverPolicy = OnePointX, StoragePolicy =
VectorPolicy<In dividual<Chromo some<Objective< 1u, Optimizator<min imize>
>, BitSetPolicy, 2>, ClockMutator]
make[2]: *** [main.o] Error 1

Thank you,

a^2

Jun 3 '07 #1
4 1776
On Jun 4, 12:32 am, aaragon <alejandro.ara. ..@gmail.comwro te:
I was unable to find out why my code is not compiling. I have a
template class and I'm trying to write the operator<< for standard
output. Does anyone know why this is not right? The code is as
follows...
Classical problem...
// main class:
template <
class Individual,
class SelectionPolicy ,
template <classclass CrossOverPolicy = OnePointX,
class StoragePolicy = VectorPolicy<In dividual>
class Population : public SelectionPolicy , public
CrossOverPolicy <Individual{

// member variables and functions
// friend declaration for standard output
template <class I,class Se,template <classclass C,class St>
friend ostream& operator<<(ostr eam& os, Population<I,Se ,C,St>& pop);
Here you declare for each instantiation of the template a
non-template function, which takes the specific instance. This
is the function that the compiler will try to call when you use
<< on the object.
};
// operator<< definition
template <class Individual,clas s SelectionPolicy ,template <class>
class CrossOverPolicy ,class StoragePolicy>
ostream& operator<<(ostr eam& os,
Population<Indi vidual,Selectio nPolicy,CrossOv erPolicy,Storag ePolicy>&
pop) {
os<<"pop"<<endl ;
return os;
}
And here you've just defined a function template. You now have
two possible functions which can be called with <<.
// main function
int main(){

typedef Population<ind, t pop;
pop ccc(10);
cout<<ccc<<endl ;
The compiler sees the two functions, the template, and the
non-template. Both are equal matches, so the non-template is
chosen. And you don't have a definition of it, so the linker
complains.
return 0;

}
The compiler error message is:

main.cxx:104: error: ambiguous overload for 'operator<<' in 'std::cout
<< ccc'
gaPopulation.h: 411: note: candidates are: std::ostream&
operator<<(std: :ostream&, Population<I, Se, C, St>&) [with I =
Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, Se = TournamentSelec tor<2>, C =
OnePointX, St = VectorPolicy<In dividual<Chromo some<Objective< 1u,
Optimizator<min imize, BitSetPolicy, 2>, ClockMutator, Individual
= Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, SelectionPolicy =
TournamentSelec tor<2>, CrossOverPolicy = OnePointX, StoragePolicy =
VectorPolicy<In dividual<Chromo some<Objective< 1u, Optimizator<min imize>>, BitSetPolicy, 2>, ClockMutator]
I wouldn't have expected ambiguous. All other things being
equal, the compiler should prefer the non-template over the
template. Of course, that would just give you a linker error,
so you wouldn't get much further.

There are two simple solutions: provide the definition for the
operator<< in the friend declaration, or provide a non-friend
template function outside the class. (A non-friend or the
operator<< definition in the class can, of course, call other
member functions, e.g. you provide a member
print(std::ostr eam&), which is called by the template function
operator<<.)

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 3 '07 #2
On Jun 3, 6:38 pm, James Kanze <james.ka...@gm ail.comwrote:
On Jun 4, 12:32 am, aaragon <alejandro.ara. ..@gmail.comwro te:
I was unable to find out why my code is not compiling. I have a
template class and I'm trying to write the operator<< for standard
output. Does anyone know why this is not right? The code is as
follows...

Classical problem...
// main class:
template <
class Individual,
class SelectionPolicy ,
template <classclass CrossOverPolicy = OnePointX,
class StoragePolicy = VectorPolicy<In dividual>
class Population : public SelectionPolicy , public
CrossOverPolicy <Individual{
// member variables and functions
// friend declaration for standard output
template <class I,class Se,template <classclass C,class St>
friend ostream& operator<<(ostr eam& os, Population<I,Se ,C,St>& pop);

Here you declare for each instantiation of the template a
non-template function, which takes the specific instance. This
is the function that the compiler will try to call when you use
<< on the object.
};
// operator<< definition
template <class Individual,clas s SelectionPolicy ,template <class>
class CrossOverPolicy ,class StoragePolicy>
ostream& operator<<(ostr eam& os,
Population<Indi vidual,Selectio nPolicy,CrossOv erPolicy,Storag ePolicy>&
pop) {
os<<"pop"<<endl ;
return os;
}

And here you've just defined a function template. You now have
two possible functions which can be called with <<.
// main function
int main(){
typedef Population<ind, t pop;
pop ccc(10);
cout<<ccc<<endl ;

The compiler sees the two functions, the template, and the
non-template. Both are equal matches, so the non-template is
chosen. And you don't have a definition of it, so the linker
complains.
return 0;
}
The compiler error message is:
main.cxx:104: error: ambiguous overload for 'operator<<' in 'std::cout
<< ccc'
gaPopulation.h: 411: note: candidates are: std::ostream&
operator<<(std: :ostream&, Population<I, Se, C, St>&) [with I =
Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, Se = TournamentSelec tor<2>, C =
OnePointX, St = VectorPolicy<In dividual<Chromo some<Objective< 1u,
Optimizator<min imize, BitSetPolicy, 2>, ClockMutator, Individual
= Individual<Chro mosome<Objectiv e<1u, Optimizator<min imize,
BitSetPolicy, 2>, ClockMutator>, SelectionPolicy =
TournamentSelec tor<2>, CrossOverPolicy = OnePointX, StoragePolicy =
VectorPolicy<In dividual<Chromo some<Objective< 1u, Optimizator<min imize>>, BitSetPolicy, 2>, ClockMutator]

I wouldn't have expected ambiguous. All other things being
equal, the compiler should prefer the non-template over the
template. Of course, that would just give you a linker error,
so you wouldn't get much further.

There are two simple solutions: provide the definition for the
operator<< in the friend declaration, or provide a non-friend
template function outside the class. (A non-friend or the
operator<< definition in the class can, of course, call other
member functions, e.g. you provide a member
print(std::ostr eam&), which is called by the template function
operator<<.)

--
James Kanze (Gabi Software) email: james.ka...@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Thank you James for your answer, I tried both ways and they work.
Something that I don't really understand is why the friend declaration
within the class is a non-template declaration? If you put the
template <template parametersbefor e the keyword 'friend', aren't you
declaring this as a template function?
Once again, thanks for the answer.

Jun 4 '07 #3
On Jun 4, 6:34 am, aaragon <alejandro.ara. ..@gmail.comwro te:
On Jun 3, 6:38 pm, James Kanze <james.ka...@gm ail.comwrote:
On Jun 4, 12:32 am, aaragon <alejandro.ara. ..@gmail.comwro te:
I was unable to find out why my code is not compiling. I have a
template class and I'm trying to write the operator<< for standard
output. Does anyone know why this is not right? The code is as
follows...
Classical problem...
// main class:
template <
class Individual,
class SelectionPolicy ,
template <classclass CrossOverPolicy = OnePointX,
class StoragePolicy = VectorPolicy<In dividual>
class Population : public SelectionPolicy , public
CrossOverPolicy <Individual{
// member variables and functions
// friend declaration for standard output
template <class I,class Se,template <classclass C,class St>
friend ostream& operator<<(ostr eam& os, Population<I,Se ,C,St>& pop);
Here you declare for each instantiation of the template a
non-template function, which takes the specific instance. This
is the function that the compiler will try to call when you use
<< on the object.
};
[...]
There are two simple solutions: provide the definition for the
operator<< in the friend declaration, or provide a non-friend
template function outside the class. (A non-friend or the
operator<< definition in the class can, of course, call other
member functions, e.g. you provide a member
print(std::ostr eam&), which is called by the template function
operator<<.)
Thank you James for your answer, I tried both ways and they work.
Something that I don't really understand is why the friend declaration
within the class is a non-template declaration? If you put the
template <template parametersbefor e the keyword 'friend', aren't you
declaring this as a template function?
Once again, thanks for the answer.
I missed them. Originally, templates couldn't be friends; this
possibility was added to the standard. And in fact, the
standard actually contradicts itself here: the first sentence of
§11.4 (Friends) says that a friend is a function or a class that
is not a member of the class, and templates are neither
functions nor classes. §14.5.3 (Friends, but in the chapter on
templates), says that a friend can be a function template or
class template, a specialization of a function template or class
template, or an ordinary (nontemplate) function or class.
There's a definite contradiction there.

I'm not sure what the compiler is doing in your case. As I
said, I was surprised that it found an ambiguïty. If I
understand your code correctly, it should declare all of the
specializations of the template function as friend. There is
also a syntax to declare just a particular instantiation as
friend, something like:
friend ostream& operator<< <>( ... ) ;
I think (although maybe the declaration of the template must
precede the class definition). I'm not really sure, however, as
I always use one of the techniques I mentionned in my first
post.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 4 '07 #4
On Jun 4, 2:16 am, James Kanze <james.ka...@gm ail.comwrote:
On Jun 4, 6:34 am, aaragon <alejandro.ara. ..@gmail.comwro te:
On Jun 3, 6:38 pm, James Kanze <james.ka...@gm ail.comwrote:
On Jun 4, 12:32 am, aaragon <alejandro.ara. ..@gmail.comwro te:
I was unable to find out why my code is not compiling. I have a
template class and I'm trying to write the operator<< for standard
output. Does anyone know why this is not right? The code is as
follows...
Classical problem...
// main class:
template <
class Individual,
class SelectionPolicy ,
template <classclass CrossOverPolicy = OnePointX,
class StoragePolicy = VectorPolicy<In dividual>
class Population : public SelectionPolicy , public
CrossOverPolicy <Individual{
// member variables and functions
// friend declaration for standard output
template <class I,class Se,template <classclass C,class St>
friend ostream& operator<<(ostr eam& os, Population<I,Se ,C,St>& pop);
Here you declare for each instantiation of the template a
non-template function, which takes the specific instance. This
is the function that the compiler will try to call when you use
<< on the object.
};

[...]
There are two simple solutions: provide the definition for the
operator<< in the friend declaration, or provide a non-friend
template function outside the class. (A non-friend or the
operator<< definition in the class can, of course, call other
member functions, e.g. you provide a member
print(std::ostr eam&), which is called by the template function
operator<<.)
Thank you James for your answer, I tried both ways and they work.
Something that I don't really understand is why the friend declaration
within the class is a non-template declaration? If you put the
template <template parametersbefor e the keyword 'friend', aren't you
declaring this as a template function?
Once again, thanks for the answer.

I missed them. Originally, templates couldn't be friends; this
possibility was added to the standard. And in fact, the
standard actually contradicts itself here: the first sentence of
§11.4 (Friends) says that a friend is a function or a class that
is not a member of the class, and templates are neither
functions nor classes. §14.5.3 (Friends, but in the chapter on
templates), says that a friend can be a function template or
class template, a specialization of a function template or class
template, or an ordinary (nontemplate) function or class.
There's a definite contradiction there.

I'm not sure what the compiler is doing in your case. As I
said, I was surprised that it found an ambiguïty. If I
understand your code correctly, it should declare all of the
specializations of the template function as friend. There is
also a syntax to declare just a particular instantiation as
friend, something like:
friend ostream& operator<< <>( ... ) ;
I think (although maybe the declaration of the template must
precede the class definition). I'm not really sure, however, as
I always use one of the techniques I mentionned in my first
post.

--
James Kanze (GABI Software) email:james.ka. ..@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
James, thank you once again for your insight on this, it has been very
helpful.

Jun 4 '07 #5

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

Similar topics

4
7155
by: franky.backeljauw | last post by:
Hello, I have a problem with using a copy constructor to convert an object of a templated class to object of another templated class. Let me first include the code (my question is below): <code:templates.h> #include <string> #include <iostream>
4
3828
by: Guenther Brunthaler | last post by:
Hi template specialists, I have a problem with the code listed below. What I wanted to do is defining an operator<< that is able to output a 'matrix<ELEMENT_T, INDEX_T>::subrange' object into a 'std::basic_ostream<charT, traits>'. For some reason, it does not work. The compiler always complains:
2
5675
by: Julian | last post by:
I would like to have output from my program to be written to cout as well as a file. (actually, i want several other output options but this should explain my problem in the simplest way). I have seen commercial programs print output to the screen as well as to a log file. depending on the user and other situations, i might want to turn off one of the outputs or maybe even both outputs. so, i want a single line with operator << function...
3
1583
by: Carlo Capelli | last post by:
I found a change in the following code, that behaved correctly in VC++ 6. #include <strstream> using namespace std; void main() { char x; ostrstream(x, 100) << "pippo" << "pluto" << ends; // here x contains "004400C8pluto"
4
2644
by: homsan toft | last post by:
I've tried the below code with MSVC and Comeau online compiler. Both complain that operator<< for Outer<part<size_t> >::inner is not defined. So how do I declare it without doing full specialization? I've tried a template on any type, like Outer<AnyT>::inner (see below) Also tried a template on the templated type: Outer<part<X> >::inner // (see below) I can't find a typo? What is the rule in operation here? Thanks, homsan
7
14910
by: glen | last post by:
Hi. I'm using GCC 4.1.1, which I mention since I don't know if this is a compiler issue, or me not understanding some subtlety in the standard. The code below compiles fine under vc++, but I'm having trouble using gcc. It's just a templated container output. /** outputs elements of a vector in the form '{el1,el2...elEnd}'
0
1318
by: Adrian | last post by:
Hi All, I am trying to create an output operator that doesnt rely on the stream type and is also polymorphic. Is there a way to combine these 2 methods so that the polymorphic output operator has template arguments. I have tried a few ways and my compiler just wont let me. Method 1: Doesn't rely on the char type of a stream --------------------------------------------------- class A
3
4256
by: Martin T. | last post by:
Hello. I tried to overload the operator<< for implicit printing of wchar_t string on a char stream. Normally using it on a ostream will succeed as std::operator<<<std::char_traits<char> will be called. However, I am using the boost::format library that internally makes use of a string stream to store the formatted string. There:
4
1888
by: =?ISO-8859-1?Q?Dar=EDo_Griffo?= | last post by:
I'm having an error with this code #include <iostream> template < typename Tclass TestOpTemplate { public: friend std::ostream& operator<< <>(std::ostream& os, const TestOpTemplate<T>& m); };
0
8388
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
8907
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8817
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...
0
8663
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...
0
7423
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6218
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
5687
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();...
1
2804
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1799
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.