Monday, March 30, 2009

comp.lang.c++ - 25 new messages in 14 topics - digest

comp.lang.c++
http://groups.google.com/group/comp.lang.c++?hl=en

comp.lang.c++@googlegroups.com

Today's topics:

* STL set lower_bound - 4 messages, 3 authors
http://groups.google.com/group/comp.lang.c++/t/aa077da047c4f4a1?hl=en
* call a C++ function from C? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/934c5e8f367583af?hl=en
* Design question: polymorphism after object creation - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/b748f0f3d941a3ba?hl=en
* specialization of member function - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/eea8c79f362a2a31?hl=en
* Does anyone else wish the C++ standards committee would give us parity with
other programming languages? - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.c++/t/65479c8a9a474e0b?hl=en
* Seeking code for temple for a <map> of enum to string - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/44eaec64edea09f4?hl=en
* Is this a good reference-counting smart pointer class? - 2 messages, 2
authors
http://groups.google.com/group/comp.lang.c++/t/41558400ad1ce160?hl=en
* Nomenclature for interger size in C/C++ - 2 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/d94de8ebc4095151?hl=en
* changing istream default delimiter - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/e6d874483e11ae85?hl=en
* please help a beginner - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/0fbb55ed651b9a60?hl=en
* usage of uin16_t - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c++/t/866a22d1cc8e35a4?hl=en
* Unignorable return value - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/3b14b8ccfba9854c?hl=en
* Standard C++ way to generate a Jump Table ??? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/7686e7082cfac191?hl=en
* Thread and C++ - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c++/t/8fd26c749a69d7ad?hl=en

==============================================================================
TOPIC: STL set lower_bound
http://groups.google.com/group/comp.lang.c++/t/aa077da047c4f4a1?hl=en
==============================================================================

== 1 of 4 ==
Date: Sun, Mar 29 2009 11:13 pm
From: mattg


Alright yea, thanks thats probably the reason why I opted with the
messy pointer storage initially. Well, to close this topic up I'd
just like to say its really counter-intuitive to design a method
called lower_bound(x) that finds the y such that x<=y. Coming from a
math background we are very strict on our usage of these technical
terms, and this could probably win an award somewhere for abuse of
notation. As you all probably know a lower bound of a number x in the
reals should be a number y in the reals such that y<=x. Guess the guys
designing STL containers slept through these classes.

On Mar 29, 9:51 pm, Obnoxious User <O...@127.0.0.1> wrote:
> On Sun, 29 Mar 2009 16:07:22 -0700, mattg wrote:
>
> [snip]
>
>
>
>
>
> > class node {
> > private:
> >         int val;
> >         int val2;
> > public:
> >         node(int v){
> >                 val = v;
> >                 val2 = 0;
> >         }
> >         int GetVal() const {
> >                 return val;
> >         }
> >         int Do() {
> >                 val2++;
> >         }
> >         bool operator<(const node& b) const {
> >                 return val<b.val;
> >         }
>
> > };
>
> > and I try calling iter->Do() I get error
>
> > test.cpp:80: error: passing 'const node' as 'this' argument of 'void
> > node::Do()' discards qualifiers
>
> > How would I work around this?
>
> Using 'new' and store pointers.
>
> --
> OU
> Remember 18th of June 2008, Democracy died that afternoon.http://frapedia.se/wiki/Information_in_English

== 2 of 4 ==
Date: Mon, Mar 30 2009 12:32 am
From: Paavo Helde


mattg <gara.matt@gmail.com> kirjutas:

> On Mar 29, 3:31 pm, Paavo Helde <pa...@nospam.please.ee> wrote:
>> mattg <gara.m...@gmail.com> kirjutas:
>>
>> > in my actual application I clean up. My original attempt at this was
>> > using node as a struct instead of a class but I couldn't figure out
>> > how to write the line
>>
>> > iter = s1.lower_bound(new node(5));
>>
>> I would write this example as:
>>
>> #include<iostream>
>> #include<set>
>>
>> using namespace std;
>>
>> class node {
>> private:
>>         int val;
>> public:
>>         node(int v){
>>                 val = v;
>>         }
>>         int GetVal() const {
>>                 return val;
>>         }
>>         bool operator<(const node& b) const {
>>                 return val<b.val;
>>         }
>>
>> };
>>
>> set<node> s1;
>>
>> void test(){
>>         s1.insert(1);
>>         s1.insert(2);
>>         s1.insert(8);
>>         s1.insert(9);
>>         s1.insert(12);
>>
>> }
>>
>> int main(){
>>         test();
>>         set<node>::iterator iter;
>>
>>         iter = s1.lower_bound(5);
>>         cout << "iter =" << iter->GetVal() << endl;
>>
>> }
>>
>>
>
> Ahh ok, thats much cleaner, but I have 2 questions:
>
> 1) does this design not cause any memory leaks

No 'new', nothing to leak.

> 2) if I add to the node
>
> class node {
> private:
> int val;
> int val2;
> public:
> node(int v){
> val = v;
> val2 = 0;
> }
> int GetVal() const {
> return val;
> }
> int Do() {
> val2++;
> }
> bool operator<(const node& b) const {
> return val<b.val;
> }
>
> };
>
> and I try calling iter->Do() I get error
>
> test.cpp:80: error: passing 'const node' as 'this' argument of 'void
> node::Do()' discards qualifiers

The things in std::set are considered immutable so by default they act as
const. If changing val2 is to be considered not to change the object
state logically (the set order is not affected, for example - this is the
case here), then you should be able to get this working as:

class node {
...
mutable int val2;
...
int Do() const { // note 'const' here
val2++;
}
};

Another way could be to use std::map<int,node> or something, instead of
std::set, depending on your goals.

Paavo


== 3 of 4 ==
Date: Mon, Mar 30 2009 12:52 am
From: Paavo Helde


mattg <gara.matt@gmail.com> kirjutas:

...
> notation. As you all probably know a lower bound of a number x in the
> reals should be a number y in the reals such that y<=x. Guess the guys
> designing STL containers slept through these classes.

Math and programming are two different things. For starters, there is no
datatype actually corresponding to real numbers.

I believe STL designers worked their design out very carefully. If
lower_bound were to return the "previous" element, then what to return if
there is none? There is no concept of an iterator "before begin()". I guess
they had a choice of introducing yet another pseudovalue in addition to end
() iterator, or demanding all algorithm users to deal with the special case
when there is no "previous element". I guess they preferred to return the
"next" iterator and avoid the problem entirely, so that only those users
who actually need the previous one are having to consider the special case.

The documentation at SGI site says that lower_bound "returns the first
position where value could be inserted without violating the ordering". So
it appers this is not lower bound of existing elements, but lower bound of
insertion places for the new element.

Regards
Paavo


== 4 of 4 ==
Date: Mon, Mar 30 2009 2:46 am
From: James Kanze


On Mar 30, 9:52 am, Paavo Helde <pa...@nospam.please.ee> wrote:
> mattg <gara.m...@gmail.com> kirjutas:

> ...

> > notation. As you all probably know a lower bound of a number
> > x in the reals should be a number y in the reals such that
> > y<=x. Guess the guys designing STL containers slept through
> > these classes.

> Math and programming are two different things. For starters,
> there is no datatype actually corresponding to real numbers.

> I believe STL designers worked their design out very
> carefully. If lower_bound were to return the "previous"
> element, then what to return if there is none? There is no
> concept of an iterator "before begin()". I guess they had a
> choice of introducing yet another pseudovalue in addition to
> end () iterator, or demanding all algorithm users to deal with
> the special case when there is no "previous element". I guess
> they preferred to return the "next" iterator and avoid the
> problem entirely, so that only those users who actually need
> the previous one are having to consider the special case.

> The documentation at SGI site says that lower_bound "returns
> the first position where value could be inserted without
> violating the ordering". So it appers this is not lower bound
> of existing elements, but lower bound of insertion places for
> the new element.

It treats the argument as the "lower bound", and and returns the
first element in the set corresponding to that lower bound:-).
(Of course, then we have problems with upper_bound.)

Seriously, IIUC, the idea is that by iterating between
lower_bound(a) and upper_bound(b), you visit all elements >= a
and < b. In other words, you've defined a (possibly empty)
sequence in the usual iterator conventions. And that possibly
empty is important; it means that if a is not a member of the
set, lower_bound(a) must equal upper_bound(a).

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

==============================================================================
TOPIC: call a C++ function from C?
http://groups.google.com/group/comp.lang.c++/t/934c5e8f367583af?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Mar 30 2009 12:39 am
From: James Kanze


On Mar 29, 1:00 pm, Pallav singh <singh.pal...@gmail.com> wrote:
> On Mar 29, 3:27 pm, Robert Hairgrove <rhairgr...@bigfoot.com>
> wrote:> Pallav singh wrote:

> > > How do I call a C++ function from C?

> > Is the function located in an external library?

> > The easiest way to do this would be to compile a separate
> > module as C++ which provides wrappers for the C++ functions,
> > exporting them as "extern C ...". Then you can link your C
> > code to those functions and don't have to worry about name
> > decoration issues.

> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> i am getting following error

> file1.cc
> extern "C" void func(int );
> void func(int i)
> {
> printf(" C++ function called %d \n", i);
> }

> file2.c
> #include <stdio.h>
> void func(int);
> void cc(int i)
> { func(i); }

> int main()
> {
> cc(1);
> return 0;
> }

> $ g++ -g file1.cc file2.c
> : In function `_Z2cci':
> : undefined reference to `func(int)'
> collect2: ld returned 1 exit status

As has already been pointed out, this is probably due to file2.c
being compiled as C++, and not as C. Another point to be aware
of is that if there is any C++ code in the program, the function
main must be compiled as C++. For something this simple, it
probably won't cause a problem, but it's undefined behavior, and
often doesn't work. (Also, you're missing some includes in
file1.cc.)

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

==============================================================================
TOPIC: Design question: polymorphism after object creation
http://groups.google.com/group/comp.lang.c++/t/b748f0f3d941a3ba?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Mar 30 2009 12:58 am
From: James Kanze


On Mar 29, 1:34 am, Marcel Müller <news.5.ma...@spamgourmet.com>
wrote:
> Balog Pal wrote:
> > "Marcel Müller" <news.5.ma...@spamgourmet.com>

> >> I am seeking for a neat solution for the following problem:

> >> There are objects of different types with a common base
> >> class, let's say folders and files (although that does not
> >> completely hit the nail on the head). These objects have a
> >> common primary key, the full qualified path. But the
> >> polymorphic type of the objects emerges only *after* the
> >> object has been referenced. See below.
> > [...]

> > I get this, but the following seem contradictory, especially
> > the observer part. If the object is not there yet why on
> > earth is it observed?

> The object is existing, but not specialized. You may request
> different kinds of information. This triggers a worker thread
> to obtain the requested information. If the object is not yet
> specialized (e.g. File or Folder) the first step is to
> determine the object type. This may require an analysis of the
> file content or the http object. Than an instance of the
> matching class is instantiated and this class fills the
> requested kind of informations. Once completed, the observer
> is notified that the information is now available. If some
> information is available fast and other information take
> longer the event may also fire twice with different flags.

Will the object be called on to change its type later, once it
has established the type the first time. If not, I'd certainly
try to defer actual creation until after the type has been
established. If you can't, or if you need to change the type
later, there's always the letter/envelop idiom. But I have a
sneaking suspicion that what you actually need is to use the
strategy pattern. You're object isn't really polymorphic with
regards to everything (the handling of the observer, for
example); what you want to do is use a delegate for the
polymorphic part, which will only be allocated once the real
type is known (and which can be freed and reallocated with a
different type, if necessary).

> In the current implementation there is a hard-coded function
> that guess the object type from the PK without any I/O. So
> File and Folder in the example can derive from Base. But this
> guess sometimes fails. This results in an object with invalid
> state.

> > From my limited understanding of the problem, I'd have
> > something like:

> > map<string, shared_ptr<Base> > repository;

> Yes, similar. But the PK is intrusive part of the object. So
> it is more like set<int_ptr<Base> > repository;

From the sound of things, these objects have the logical
equivalent of a static lifetime (i.e. they are created on
program start-up, and live until program shutdown). If this is
the case, why do you want a smart pointer? It doesn't buy you
anything, and it sends the wrong message to the user. (If you
use the strategy pattern, an std::auto_ptr or a
boost::scoped_ptr in the base object might make sense,
especially if you have to change the strategy dynamically.)

> > As the only info up front is PK, in this phase you just put
> > that in the map, the ptr is null, signaling the not-accessed
> > state.

> Even an object, that is not fully complete, has some basic
> properties. It may be selected, it may be referenced, it has
> a changeable display name and so on. NULL is not sufficient.

In other words, your base class has some behavior. Logically,
this means either the template method pattern or the strategy
pattern---the latter means that you can defer the decision, and
change the implementation at will.

[...]
> A union with a few types and a stable common base class would
> be nice. If the base is virtual, the memory layout could
> match the requirements in theory - but only in theory.
> Like this:
> +------------------------+
> | Base |
> +-------+--------+-------+
> | File | Folder | Other |
> +-------+ | |
> + free | +-------+
> +-------+--------+-------+

> This could turn into 4 different classes (if Base is not
> abstract) without the need to change the Pointer to Base.

This can be made to work, but only if there are no pointers to
the object which outlive the change of type. In other words, if
you use some sort of smart pointer, with an additional
indirection so that there is only one instance of the pointer to
the actual object, and if all of the type changes go through the
smart pointer---the function which changes the type should
return this, and the smart pointer use the return value to
"update" its pointer.

Quite frankly, it sounds like a maintenance nightmare. I'd go
with the strategy pattern.

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


== 2 of 2 ==
Date: Mon, Mar 30 2009 1:23 am
From: "Alf P. Steinbach"


* James Kanze:
> On Mar 29, 1:34 am, Marcel Müller <news.5.ma...@spamgourmet.com>
>
>> Even an object, that is not fully complete, has some basic
>> properties. It may be selected, it may be referenced, it has
>> a changeable display name and so on. NULL is not sufficient.
>
> In other words, your base class has some behavior. Logically,
> this means either the template method pattern or the strategy
> pattern---the latter means that you can defer the decision, and
> change the implementation at will.

As I wrote else-thread, IMHO it's not a good idea to add complexity just for
ideological reasons. Objects that modify themselves to provide richer
functionality, where that metamorphosis is (1) costly and (2) can fail, well
it's just silly. Instead keep the distinction between URI or directory entry or
whatever, on the one hand, and what's referred to, on the other hand. They might
implement some common interface. But I can't for the life of me see the point in
having e.g. a directory entry metamorphose into a file it represents.

Having said that, I also have an issue with this "pattern talk". Some few
patterns are very often needed in C++ because C++ doesn't provide the relevant
support, e.g. visitor pattern. But I had to look up "strategy pattern" and
darned if I can see what's different from "template pattern"; I guess it's some
detail that Someone thinks is important, like maintaining red Fords are
intrinsicially different from blue Fords, hey even a child can see difference.

Also, I really don't see how it can be helpful for the OP's question to be able
to dynamically replace the implemententaion of a method or set of methods. It's
not like he just wants the behavior of methods to change. He wants dynamic
switching between different but overlapping sets of behaviors, which means
complexity and ample opportunities for bugs to creep in and start families.


Cheers,

- Alf

--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!

==============================================================================
TOPIC: specialization of member function
http://groups.google.com/group/comp.lang.c++/t/eea8c79f362a2a31?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Mar 30 2009 1:06 am
From: abir


Hi,
I have a template my_class which has a bool value template parameter
along with several type template parameters.

For a non template member function foo of the above , i want to have
any one
of the two brunch code executed.

template<typename T,typename P,bool m>
class my_class
{
void foo()
{
if(m)
{
execute first branch.
}
else
{
execute second branch.
}
}
};

as a present it uses runtime if/else to go to either first branch or
second branch with the hope that
as the compiler knows the value of m at the compile time, it can
eliminate the dead branch.

i can't use enable if as foo is a non template member (or any way it
can be done ?)
i can't use member specialization (directly) as my_class itself is a
template. In that case i have to take help of another helper class.
mpl if is another option , like if_<m,branch1,branch2>::type::execute
();
but again , i have to write a few classes , make some friends for
internal data access etc.

is there any simpler option (like D static if ?) exists ? ot which
one is the best option ?

thanks
abir


== 2 of 2 ==
Date: Mon, Mar 30 2009 1:43 am
From: Michael DOUBEZ


abir wrote:
> Hi,
> I have a template my_class which has a bool value template parameter
> along with several type template parameters.
>
> For a non template member function foo of the above , i want to have
> any one
> of the two brunch code executed.
>
> template<typename T,typename P,bool m>
> class my_class
> {
> void foo()
> {
> if(m)
> {
> execute first branch.
> }
> else
> {
> execute second branch.
> }
> }
> };
>
> as a present it uses runtime if/else to go to either first branch or
> second branch with the hope that
> as the compiler knows the value of m at the compile time, it can
> eliminate the dead branch.
>
> i can't use enable if as foo is a non template member (or any way it
> can be done ?)
> i can't use member specialization (directly) as my_class itself is a
> template. In that case i have to take help of another helper class.
> mpl if is another option , like if_<m,branch1,branch2>::type::execute
> ();
> but again , i have to write a few classes , make some friends for
> internal data access etc.
>
> is there any simpler option (like D static if ?) exists ? ot which
> one is the best option ?

There is the solution of function overloading from Andrei Alexandrescu
(Modern C++). You create a type BoolToType<bool> and use it to create
overloaded functions:

template<bool>struct BoolToType{};


template<typename T,typename P,bool m>
class my_class
{
void foo()
{
return foo(BoolToType<m>());
}

void foo(const BoolToType<true>&)
{
execute first branch.
}
void foo(const BoolToType<false>&)
{
execute second branch.
}

};

--
Michael

==============================================================================
TOPIC: Does anyone else wish the C++ standards committee would give us parity
with other programming languages?
http://groups.google.com/group/comp.lang.c++/t/65479c8a9a474e0b?hl=en
==============================================================================

== 1 of 3 ==
Date: Mon, Mar 30 2009 1:28 am
From: James Kanze


On Mar 29, 2:07 pm, Christof Donat <c...@okunah.de> wrote:

> > As I said, I've yet to find anything important that I could
> > do in Java that I couldn't do in C++, and I've extensive
> > experience in both languages.

> I'd say, e.g. writing web applications in C++ is a bit more
> difficult than just hacking a servlet.

And I'd agree. But it's not a language problem, and probably
not even a library problem. The existing infrastructure in web
servers is designed to support Java; it's not designed to
support any compiled language. If there were a demand for it,
it probably wouldn't be that hard to implement a server which
supported C++, but typically, the code the server addresses
directly consists of a lot of small, constantly changing modules
(Java beans)---something where the weaknesses of Java aren't
really significant.

> Of course it is not impossible, but it is hard compared to
> Java. On the other hand hacking a servlet is more complicated
> than hacking a PHP script and PHP nowadays is powerfull enough
> to even crete bigger web applications.

Whatever happened to JSP?

> So this is just an type of application where I wouldn't prefer
> to use C++ at the moment.

There are lots of applications where I choose some other
language; I've probably written more lines of AWK or Bourne
shell in the last year or two than C++. And if I were doing a
lightweight GUI client, I'd probably choose Java, simply because
Swing seems better than either wxWidgets or Qt. (Admittedly,
that might be mainly because I know it better, but the little
bit I've seen of wxWidgets hasn't impressed me, and I don't
really like Qt's policy of an additional preprocessor.) Also,
it's the type of application where Java's portability of
compiled code could be an advantage. Of course, all of this is
perfectly possible in C++: the GUI libraries are there, and
there's certainly nothing to stop a vendor from implementing C++
in a VM. (And portability isn't always an issue---more than a
few companies standardize on Windows on a PC for their client
machines.)

> > You claimed that there were things you could do in Java, but
> > not in C++. I asked you to back up that claim. Obviously,
> > you can't.

> Of course it is enough to know, that C++ is turing complete.

Yes and no. I considered pointing that out, but I think that
there's a real sense that it's irrelevant. Java is also Turing
complete, but there are more than a few things that you can't
write in Java. Turing complete only concerns the actual
calculations---the fact that a language is Turing complete
doesn't necessarily mean that you'll be able to write device
drivers in it, for example. (And of course, you can't write the
kernel code which does the context switching in either Java or
C++.)

> I guess his point was more on things that are a lot easier to
> do in Java than in C++.

His point is not at all clear. My postings have tried to make
him make it clear, by asking him what he means---what can you do
in Java that you cannot do in C++, or at least, what does he
have in mind. Especially given his mention in the header of the
standards committee: the standards committee doesn't address
larger environment issues; there's nothing that the standards
committee could do, for example, to force web servers to give
C++ the same level of support they give Java.

There are certainly cases where other languages are to be
preferred; as I said, I've probably written more lines of Bourne
shell and AWk than C++ recently. But I fail to see any "lack of
parity", nor anything that the committee can or should do in
this respect. There are some important pieces missing: C++
doesn't have a decent module system. But then, Java (and C#?)
are even worse in this respect; using header files, you can at
least fake it in C++. And it would certainly help if garbage
collection were standand, rather than a third party library, and
threading did come a bit late---doubtlessly due to aleas of the
schedule. It was too soon to add it in the last version of the
standard, which means effectively waiting 10 years. But it's
quite possible to use garbage collection or threading in C++
today---a fair number of people use garbage collection, and I'd
guess that most use threading. In theory, both require some
support from the standard, but in practice, all of the existing
implementations do avoid things that would prevent them from
working, even if the standard doesn't require it.

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


== 2 of 3 ==
Date: Mon, Mar 30 2009 4:46 am
From: Christof Donat


Hi,

> On Mar 29, 2:07 pm, Christof Donat <c...@okunah.de> wrote:
>
>> > As I said, I've yet to find anything important that I could
>> > do in Java that I couldn't do in C++, and I've extensive
>> > experience in both languages.
>
>> I'd say, e.g. writing web applications in C++ is a bit more
>> difficult than just hacking a servlet.
>
> And I'd agree. But it's not a language problem, and probably
> not even a library problem. The existing infrastructure in web
> servers is designed to support Java;

No. Most installed web servers use apache as server software. Apache doesn't
support java without any additional modules and an external server process,
but apache supports C modules without any changes. It is a problem of the
API. The apache module API is - well - a bit more complicated thant the
servlet API.

I agree with you, that it is not a language problem, but I think it is a
library problem.

> it's not designed to support any compiled language.

Well, C is a compiled language, isn't it? Apart from the apache module
interface the CGI interface as well as the FastCGI Interfacce is completely
language agnostic. You could even write CGI scripts in Java - just that it
will start the whole VM for every request. The difference is that scripting
languages like Perl, Python or Ruby come with an API that supports easy
writing of portable CGI applications.

> If there were a demand for it,
> it probably wouldn't be that hard to implement a server which
> supported C++,

Web developers care much about not binding themselves to a speciffic
implementation. Java servlets work with any servlet container, not just
tomcat. CGI scripts written in Perl work anywehere where a Perl interpreter
is available and the Webserver supports the CGI interface (virtually any).
PHP scripts just need one of three ways to get the PHP interpreter run:
apache module, CGI or FastCGI.

As an example why this might be important: beginning with version 2 apache
supports multithreaded operation in contrast to just multiple processes. The
PHP apache module does not. whenever you whant to use the PHP apache module
you must go back to processes. For a customer we switched to the FastCGI
Version of PHP without any code changes. Then we could use a multithreaded
MPM module which increased the throughput of the server more than one order
of magnitude on the same hardware.

> but typically, the code the server addresses
> directly consists of a lot of small, constantly changing modules
> (Java beans)---something where the weaknesses of Java aren't
> really significant.

That is not true as well. Typically a web application itsself doesn't change
too much if it is well thought out. Maybe some bugs are fixed or some
components are added once in a while, but usually nothing changes all the
time. Some of the weaknesses of Java are the reason why there is a servlet
API and not just CGI.

Actually I think, C++ as a language and as a runntime environment as much
more potential for web applications than Java ever had, but there is no easy
to use portable API:

1. There is the possibility of writing apache, IIS, whatever sever modules.
The drawback is that you are tied to apache, IIS, whatever then.
Additionally these APIs are usually not really too simple.

2. The second way is to use CGI. Then for every request a process will be
spawned and the application will be started. That is OK for small things,
but as soon as your program becomes more complex, you have long startup
times, can't share ressources over multiple requests (e.g. DB connections)
and have to use usually platform speciffic shared memory APIs to facillitate a
fast communication between parallel requests.

3. The third way is FastCGI. With FastCGI all the drawbacks of server
modules and CGI can be solved, but my understanding of "easy to use" is
something very different.

>> Of course it is not impossible, but it is hard compared to
>> Java. On the other hand hacking a servlet is more complicated
>> than hacking a PHP script and PHP nowadays is powerfull enough
>> to even crete bigger web applications.
>
> Whatever happened to JSP?

There still seem to be some people out there using it, but it has proven to
be the worst of two worlds. Well designed web applications that should stay
so usually don't use JSP. Whenever you use JSP as view abstraction in a
application that will be maintained by multiple developers, someone will
come along and put code into the JSP that doesn't belong in the view, but in
the application layer.

As you see, JSP is considered harmfull. Use explicit template systems like
e.g. XSLT instead.

Of course the same thing happens with PHP, but that is just a basic language
problem of PHP that Java itsself doesn't have. Why add it?

> And if I were doing a
> lightweight GUI client, I'd probably choose Java, simply because
> Swing seems better than either wxWidgets or Qt.

Actually I'd prefer either XUL/XBL/JavaScript or Python/PyQt.

> there's nothing that the standards
> committee could do, for example, to force web servers to give
> C++ the same level of support they give Java.

As I said, I don't think it should be in the standard. A well defined API,
like WSGI for Python as a start, and a fiew implementations that are as
portable as possible and can use various server APIs (e.g. apache module,
FastCGI and CGI) or run as a minimal stand allone HTTP server would be a
good beginning. Not in the standard, but very closely related to it.

How could this happen? The committe I guess has a lot of more important
things to do. So maybe we could find some interested people and first describe
such a API and then implement it. If the committe spreads the word of that
API as the state of the art way of implementing web applications with C++,
that would be great support for their part.

Christof


== 3 of 3 ==
Date: Mon, Mar 30 2009 4:00 am
From: ytrembla@nyx.nyx.net (Yannick Tremblay)


In article <12c8d09c-9a90-4dd4-9b48-c52262e4f55e@k19g2000prh.googlegroups.com>,
Anonymous Infidel <messiah2999@yahoo.com> wrote:
>> >Or better yet, force them(C#, Java, etc) to do the catch up game....
>>
>> Might be useful if you would clarify what in your mind is making the
>> C++ language trail behind these other languages.
>Simple...That would be all the things they can do that C++ can't.
>
>Note: You can use Google to see the differences between C++ and other
>programming languages.

You know, there's a difference between constructive criticism or
starting a worthwhile discussion on possible improvements to the C++
language and moaning or trolling. At your post stand, I am afraid I
can't classify them as constructive criticism...

Of course C++ is not perfect but no language is. You can use Google
to search anything about anything. You can use google to search for
the difference between Java and other programming language.

If you are really interested in improving on the flaws of C++, then
please start discussing about some features that say you like in Java
and you would like to see in C++. Who knows, there might be a simple
way to do it, someone may have written or be motivated to write a
library to solve this flaw or this discussion might even lead to a
proposal to the standard committee. Your posts as they stand lead to
nothing useful.

Yannick

==============================================================================
TOPIC: Seeking code for temple for a <map> of enum to string
http://groups.google.com/group/comp.lang.c++/t/44eaec64edea09f4?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Mar 30 2009 2:01 am
From: James Kanze


On Mar 29, 10:18 pm, "AnonMail2...@gmail.com" <AnonMail2...@gmail.com>
wrote:
> On Mar 15, 11:04 pm, Baron Samedi <Papa.Legba....@gmail.com> wrote:

> > I know that it's an old one - how to take an enum value and
> > output astring.

> > I'd like to make it a template class, so that I can add to it in a
> > general manner.

> This is a common task. Of course, inside you program,
> library, or collection of libraries you want to just use your
> enumerator. But what you've defined as an enumerator may come
> in from the external world as text.

> Textual representation also comes in handy for error messages
> and when serializing data. Serializing an enumerator as an int
> is a future maintenance nightmare just waiting to happen.
> Doing so means you can't change the value of an emuerator
> without worrying about breaking something.

Well, the obvious answer to that is "don't change them":-).
Seriously, you do need some sort of versioning, even if you're
using text represtations for serialization, since you have to
deal with enum values being added and removed. (Of course, all
of the other arguments for textual representation still hold.
Reading "operationPending" for the state, rather than "5", makes
debugging considerably easier.)

> What we have done is implement three template functions for each
> enumerator.
> Here are their signatures:

> // convert a string to an enumerator - throw an exception if the
> string is invalid
> template <class T>
> T stringToEnum (const std::string & s)

> // convert a string to an enumerator
> // on success, return true and set t; on failure, return false and t
> is not touched
> template <class T>
> bool stringToEnum (const std::string & s, T & t)

> // convert an enumerator to string (actually const char *)
> template <class T>
> const char * enumToSTring (T t);

Just a question: you have generic templates to do this? I can't
see how (but maybe I've missed something).

In my case, I use a (originally) simple program, capable of
understanding enough C++ to parse the enums, to generate the
implementations of these. Also, I've found that the template
solution poses some problems, mainly with regards to namespaces;
my solution has been to generate functions toString( EnumType )
and to<EnumType>( string ). And a third, fromString( string,
EnumType& ) for use in templates. (Having the EnumType in an
argument makes the function name dependent, and causes ADL to
kick in.) These functions are generated in the same namespace
as the enum.

I originally used the template approach, but couldn't find an
appropriate namespace to put it in. (More exactly, I orginally
implemented the code as part of my library, with the templates
in the same namespace as the library code. This version is
available at my site: http://kanze.james.neuf.fr/code-en.fr. I
have since changed the implementation to remove all dependencies
on my library in the generated code. Having done this, I didn't
want it to use the namespace Gabi, and I couldn't find another
appropriate namespace for the templates. I actually liked the
idea of naming the function templates string_cast, and putting
them in global namespace, but I was too worried about possible
conflicts with other code.)

FWIW, the current implementation has options to generate either:
Gabi::Util::Fallible< std::string > toString( enum_type ) ;
Gabi::Util::Fallible< enum_type > toenum_type( std::string
const& ) ;
bool fromString( enum_type&, std::string const& ) ;
(for myself and others using my library) or
char const* toString( enum_type ) ;
enum_type const* toenum_type( std::string const& ) ;
bool fromString( enum_type&, std::string const& ) ;
(With enum_type being the type of the enum, of course). When
all is said and done, however, I think that in this case, using
Fallible instead of pointers may be overkill.

> Internally these are implemented using a static array of pairs
> of const char * and enumerators. Using a static array of POD
> means there are no of order of initialization or thread safety
> issues that you might encounter using a std::map (for
> instance) or other C++ class.

Agreed. At one point, I toyed with the idea of having two
std::map at the interface level, so that users would have a well
known interface to deal with, rather than something I define
myself. In the end, both order of initialization and naming
problems lead me to abandon this approach.

> Lookup is done using linear search. We've never had any
> performance issues with this. When converting from string to
> enumerator we use case insensitive compares.

That's an interesting idea. Sounds like I'll have to add an
option to my generator.

> Different strings can be mapped to the same enumerator value
> if needed.

And different enumerators to the same string?

> When converting from enumerator to string the first entry in
> the array will be the "preferred" text representation.

I do a one to one mapping, but at the symbolic level (name
to/from string); if two enum constants have the same value, then
I handle it as you do---first match is used.

I also permit (in the current versions) transformations in the
name, mainly because I had code available which supported this
already, and I've encountered places which had special naming
conventions for enum constants, that you possibly wouldn't want
to appear in the external representations.

> What's more, we've hidden all of the implementation by
> explicitly instantiating each function inside the
> implementation file. The user of the functions never see
> anything but the plain old enumerator and the signature of the
> above classes.

So you do have an explicit specialization for each enum. Hand
written, or automatically generated?

Note that for the code to be conform, you do need for a
declaration of the specification to be visible anytime it is
used.

> These functions go a long way to solving the enumerator to
> string and string to enumerator task. With them, writing an
> operator<< or operator>> is trivial.

> The code is done at work - I will ask if it is ok to post it.

But the code is probably simpler than defining the interface:-).
A simple struct, a couple of predicates, and std::find_if should
do the trick.

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

==============================================================================
TOPIC: Is this a good reference-counting smart pointer class?
http://groups.google.com/group/comp.lang.c++/t/41558400ad1ce160?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Mar 30 2009 2:09 am
From: James Kanze


On Mar 29, 11:48 pm, douglas <Protoman2...@gmail.com> wrote:
> On Mar 29, 12:46 am, Juha Nieminen <nos...@thanks.invalid> wrote:

> > douglas wrote:
> > > So, how do I fix it?

> > Share the reference counter with all the copies, rather than
> > replicating it.

> Or could I modify the classes to have a mutable ref count
> variable, and have the SmrtPtr class add and subtract from
> that, and free the ptr when that var hits 0. Would that be
> intrusive ref counting?

That's what is meant by intrusive reference counting, yes.

The version having the separate counter object (from Barton and
Nackman, for example) has the advantage that it works with all
types of objects, even ones in the standard or some third party
library. On the other hand, it is extremely fragile---it's far
too easy to end up with two counter objects. For this reason, I
would avoid it at all cost in critical code. The invasive
version (from Scott Meyers, for example) typically requires that
the pointed to object ultimately derive from a base class
containing the counter. This means that you can't use it on
existing classes directly (but it's trivial to wrap an existing
class so that you can use it); it also has implications when
multiple inheritance is involved. On the other hand, it's
fairly robust. (As robust as reference counting can be.)

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


== 2 of 2 ==
Date: Mon, Mar 30 2009 2:41 am
From: Christian Kandeler


Protoman wrote:

> Is this a good reference-counting smart pointer class?
>
> // begin code
>

[ .. ]

> operator T*()const {if(ptr==0)throw NullPtr();else return ptr;}

In addition to what others have said, I wonder why your class throws an
exception on implicit conversion of a null pointer. Why should this be
illegal?

Christian


==============================================================================
TOPIC: Nomenclature for interger size in C/C++
http://groups.google.com/group/comp.lang.c++/t/d94de8ebc4095151?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Mar 30 2009 2:20 am
From: James Kanze


On Mar 29, 1:02 pm, Giuliano Bertoletti <gbe32...@libero.it> wrote:
> Vaclav Haisman ha scritto:

> >> You quickly realize that one or probably both programmers
> >> will loose their job if you agree with the upgrade.

> >> Would you still believe it's worth profitting the better
> >> optimization today compilers can do for you ?
> > This is total bullshit. You do not have to stop developing
> > new features or stop maintaining old code. This can be done
> > in parallel with normal development.

> We may discuss whether my estimates are a bit too pessimistic,
> but once we estabilish that it takes N days to upgrade and
> test (provided the forecast is correct), that is the time (not
> less, possibly more).

> It really doesn't matter how you interleave the upgrading with
> the development time or even how you divide the work among
> programmers.

> At the end of the year, N days (or more due to task switch
> overhead) have been consumed for the upgrade.

Certainly. On the other hand, not upgrading has its costs as
well. In the case of VC++ 6.0, those costs are, IMHO, quite
high---the newer versions of the compilers are known to be
significantly better in terms of less bugs.

> > What you do is that you create parallel projects for VC9 out
> > of the VC6 projects. Getting things to compile usually
> > requires only very little editing. Even huge projects with
> > millions of lines of code usually take only very little
> > tweaking for the code to become compilable.

> - First, compilable doesn't mean it'll work.

> Suppose I somewhere serialize a structure to disk like this:

> fwrite(&mys, 1, sizeof(mys), h1); // C struct serialization

Then you're in deep trouble, regardless of what you do.

> are you sure the new compiler packs the structure in the same
> way ?

Given the same options, probably. Given different compiler
options, then even VC++ 6.0 will pack structures differently.

> This is a potential problem which goes unnoticed at compile
> time. You may object, I should have not serilized the struct
> that way in the first place.

> Maybe, but if for example I serialize each member I would
> probably loose efficiency (repeated calls to the OS) which may
> or may not be critical. Again, it's a choice.

Not really. Correct serialization isn't very expensive (except
for double), and is a lot easier to read, understand and
maintain. And it certainly doesn't involve any more called to
the OS---there should be exactly one (and only one) per
transactional record.

[...]
> I'm not saying it's never worth the effort, but I would like
> to see more detailed statements about supporting the upgrade
> rather than simply: "the compiler works better, has many more
> features and is compliant with the standard".

> Which features ? Do we need them ?

> These are the first questions you face when you step that way.

Certainly. In the case of VC++ 6.0: the compiler is known to be
very, very buggy with regards to templates. If your code makes
any use of templates, the slightest change in the code (or in
the compiler options) could cause the compiler to generate
incorrect code. Which is very expensive to debug. And
(partially because of the problems with templates) the library
delivered with VC++ 6.0 was fairly simplistic---the library
delivered with later versions has a lot of options which help
you find errors quicker. If you're using the standard library,
you should definitely upgrade.

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


== 2 of 2 ==
Date: Mon, Mar 30 2009 2:27 am
From: James Kanze


On Mar 29, 7:31 pm, Giuliano Bertoletti <gbe32...@libero.it> wrote:
> Balog Pal ha scritto:

[...]
> Consider for example the (wrong) assumption that global
> objects are initialized in a particular order.

Consider that adding or removing a module in the link phase may
change that order, even if you don't upgrade. Not upgrading is
a very valid option is all you're doing is limited bug fixing;
i.e. the product's life is pretty much over. Otherwise, not
upgrading probably costs more (in cases where you're using a
compiler that old---not in every case, of course) than
upgrading.

> > Well, if they are truly satisfiesfied -- and not just
> > suffering silently form the same lock-in.

> > In my practice I met many situations where 'customer
> > satisfection' brought very different results if you asked a
> > manager who paid for the stuff and the users in everyday
> > work.

> What I mean is that software is buggy. Patches and service
> packs keep being release to correct defects. A programmer
> should try to minimize the impact of bugs, whatever the means.

> As soon as they're spotted they must be corrected and a
> defensive programming style is also preferable.

> But you should also limit the risks of triggering dormant bugs
> if possible.

One way of doing that is precisely by upgrading to a compiler
which is stricter in its interpretation of the language. The
more different compilers you've used, the greater the chance
that one of them triggers the bug in your test code, rather than
letting it sleep until the software is at the customer site.

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

==============================================================================
TOPIC: changing istream default delimiter
http://groups.google.com/group/comp.lang.c++/t/e6d874483e11ae85?hl=en
==============================================================================

== 1 of 1 ==
Date: Mon, Mar 30 2009 2:39 am
From: James Kanze


On Mar 30, 4:50 am, "Amadeus W.M." <amadeu...@verizon.net> wrote:
> Is it possible to change the space delimiter in an istream to,
> say, a comma? I'm thinking facets, locales and imbue. I want
> to read a comma separated file in the exact same way as if it
> were tab delimited. If yes, how would I do that?

> I know how to do it with get/getline and the like. Changing
> the delimiter in the input string just seems more elegant.

Or more confusing to the reader.

You can modify the locale to consider commas (and only commas)
whitespeace. This still won't allow you to read CSV, since it
will treat commas in a quoted string as separators, and will
treat empty fields (two successive commas) as non-existant.

It's also a hack, and abuse of the locale. As such, it can only
server to confuse the reader.

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

==============================================================================
TOPIC: please help a beginner
http://groups.google.com/group/comp.lang.c++/t/0fbb55ed651b9a60?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Mar 30 2009 3:01 am
From: DerTopper@web.de


On Mar 30, 2:03 am, ED <edym...@gmail.com> wrote:
> Hey people... I'm new in C programing, and i'm having some problem.
> What's wrong with the code below. I got no error compiling the file,
> but when executing i get a *** glibc detected *** ./test: double free
> or corruption (out): 0xbfe83468 *** error:
>
> It's a simple code:
>
> //file config.c
>
[snip]
> int read_server_list(char *config_file, char **servers)
> {
[snip]
>                         for(i = 0; i < MAX_SERVERS; i++)
>                         {
>                                 servers[i] = (char *) malloc(MAX_CHAR_LINE);
>                                 fgets(servers[i], MAX_CHAR_LINE, file);
>                                 printf("%s",servers[i]); //prints OK
>                         }
[snip]
> }
>
> void cleanup_server_list(char **servers)
> {
>         int i = 0;
>         do {
>             free( servers[i] );
>             servers[i++] = NULL;
>         } while( i < MAX_SERVERS );
>
>         free( servers );
>         servers = NULL;
>
> }
>
> and then
>
> //file main.c
>
> #include <stdio.h>
> #include "config.h"
>
> int main()
> {
>
>         int status;
>         char *file = "text.txt";
>         char **servers;
>         status = read_server_list(file, servers);
>
>         cleanup_server_list(servers); // HERE I GET THE ERROR
> }

Let's explain Alf's answer a bit more detailed: You should pass the
address of a pointer as second argument to read_server_list.
Replace
char **servers;
status = read_server_list(file, servers);
by
char *servers;
status = read_server_list(file, &servers);
and you'll do just fine. The difference between those two is that the
variable servers in the second version is a pointer will point to the
newly allocated memory after read_server_list has been called.

The first version will pass a pointer to a pointer to the function.
Since this pointer is not initialized, but de-referenced inside the
function, you'll get undefined behaviour (most time you'll be lucky,
but your code may produce an Access Violation from time to time).

Regards,
Stuart


== 2 of 2 ==
Date: Mon, Mar 30 2009 4:41 am
From: ytrembla@nyx.nyx.net (Yannick Tremblay)


As Alf already pointed out, if you are looking for C specific answers,
post to a C specific group.

In article <4b67eba4-34f4-46d6-8408-cf0dcbfb3fc6@a7g2000yqk.googlegroups.com>,
<DerTopper@web.de> wrote:
>On Mar 30, 2:03 am, ED <edym...@gmail.com> wrote:
>> Hey people... I'm new in C programing, and i'm having some problem.
>> What's wrong with the code below. I got no error compiling the file,
>> but when executing i get a *** glibc detected *** ./test: double free
>> or corruption (out): 0xbfe83468 *** error:
>>
>> It's a simple code:
>>
>> //file config.c
>>
>[snip]

>Let's explain Alf's answer a bit more detailed: You should pass the
>address of a pointer as second argument to read_server_list.
>Replace
> char **servers;
> status = read_server_list(file, servers);
>by
> char *servers;
> status = read_server_list(file, &servers);
>and you'll do just fine. The difference between those two is that the
>variable servers in the second version is a pointer will point to the
>newly allocated memory after read_server_list has been called.
>
>The first version will pass a pointer to a pointer to the function.
>Since this pointer is not initialized, but de-referenced inside the
>function, you'll get undefined behaviour (most time you'll be lucky,
>but your code may produce an Access Violation from time to time).

I'll give you another hint extremely useful for new programmers and
IMO useful for experinced programmers too:

Initialise all of your variable at decaration time especially
pointers.

So that should give:

char *servers = 0; // NULL if you prefer
// ...
FILE * pFile = 0; // NULL if you prefer
// ...
int status = -1;

Etc.

This is a very good habit to take but is unfortunately not very
popular with C programmers but will save you lots of hassle in your
life as a programmer.

Yannick


==============================================================================
TOPIC: usage of uin16_t
http://groups.google.com/group/comp.lang.c++/t/866a22d1cc8e35a4?hl=en
==============================================================================

== 1 of 2 ==
Date: Mon, Mar 30 2009 3:06 am
From: Pavan


Hi Can you clarify following questions regarding uint16_t

1> Does uint16_t is supported by Windows compilers also? If not on
checking what define, I should typedef. I mean to say for eg:
#ifdef WIN32
typedef unsigned short uint16_t;

No comments: