[prog] C++ strange linking behaviour
Wolfgang Petzold
petzold at villa-chaos.de
Tue Nov 9 07:52:17 EST 2004
Am 11/08/2004 03:23 PM schrieb Kathryn Hogg:
>> g++ -Wall -g -c -o someclass.o someclass.cxx
>
> This is the crux of the problems. someclass.cxx only contains template
> definitions. As such, compiling this file doesn't really do anything.
>
> Furthermore, the way that template instantiation works on most platforms
> requires that you see all the template definitions at compile times. So
> all the code in someclass.cxx should be in the header file.
That's for *template* classes only, right? If I include the
implementation of non-template class methods more than once I will
get a "multiple definition" error ... Yeah, I think I see. Thank you
both, Miriam and Kathryn.
On a more general level, I'm still a bit confused, though. I always
thought, header files are where declarations and prototypes go, and the
actual implementations go into another file. It's not a matter for me
now (and probably won't be in the near future), but if I were selling a
C++ template library I would have to give out the implementation code,
too (the "templated" parts of it), for the library to be able to be
used. Is this right?
> BTW, for printing containers try the following
>
> std::set<int> s;
> std::copy(s.begin(), s.end(), std::ostream_iterator<int>(cout, " "));
I will consider this. Probably this (or at least something quite
similar) is just the crucial part of what I thought would have to
go into my as_string() method. And if it is of type void and does
the actual printing itself, I won't care. That's not the point.
> or if you just want to do
>
> std::cout << s << std::endl;
>
> try
>
> template <class T>
> struct printer
> {
> const T &t;
> char char *sep;
> printer(const T &_t, const char *s = " "): t(_t), sep(s)
> {}
> }
>
> template <class T>
> ostream &operator << (ostream &os, const printer<T> &p>
> {
> std::copy(p.t.begin(); p.t.end(),
> std::ostream_iterator<T>(os, p.t.sep);
> return os;
> }
>
>
> and then call
>
> std::cout << printer<int>(s) << std::endl;
Wow. [Trying to reach for something to say...] Wow.
Is there something like a "C++ one-liner of the month"-thing going on
somewhere? Who said that /perl/ was the hard-to-read-language? OK, just
kidding. But I'm impressed, really.
Thanks again,
Wolfgang
More information about the Programming
mailing list