Topic: Virtual static functions !?!


Author: anonimo@terra.es ("Juan")
Date: Wed, 24 Sep 2003 15:23:41 +0000 (UTC)
Raw View
"Francis Glassborow" <francis@robinton.demon.co.uk> escribi    en el mensaje
news:oE6$1oF76Bc$EwwU@robinton.demon.co.uk...
>
> And my understanding is that a.callStatic() is entirely synonymous (i.e.
> completely interchangeable) with A::callStatic() and as such there is no
> case where the former syntax is required.
>
I don't understand why this syntax is allowed. It's unnecesary and obscures
the code because the reader can think that callStatic does something with a.


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: ng@spfweb.co.uk (Steve Folly)
Date: Thu, 25 Sep 2003 02:18:52 +0000 (UTC)
Raw View
On 23/9/03 7:54 pm, in article 1064323094.157945@master.nyc.kbcfp.com,
"Hyman Rosen" <hyrosen@mail.com> wrote:

> In the obvious implementation, static virtual methods get a vtable slot,
> and invoking the method through an object is done by dispatching on the
> type of the object, but the methods are not passed a 'this' pointer.

This implies a flag of some kind in the vtable to indicate whether or not to
pass a 'this' pointer for the particular method.

If this is added,  I would imagine quite a lot of already-compiled-code
would break when linked with new code? (If not all of it!)  Which, I think
you'd agree is one good reason NOT to introduce them.



--
Regards,
Steve.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: brangdon@cix.co.uk (Dave Harris)
Date: Fri, 26 Sep 2003 03:00:20 +0000 (UTC)
Raw View
hyrosen@mail.com (Hyman Rosen) wrote (abridged):
> In the obvious implementation, static virtual methods get a vtable
> slot, and invoking the method through an object is done by
> dispatching on the type of the object, but the methods are not
> passed a 'this' pointer.

So calling other virtual statics doesn't work?

    struct Base {
        virtual static int func() { return func2(); }
        virtual static int func2() { return 1; }
    };

    struct Derived : Base {
        virtual static int func2() { return 2; }
    };

    void test() {
        Derived d;
        Base &b = d;
        cout << b.func();
    }

If this doesn't output "2", then "virtual" is meaning something
strange. I was expecting virtual statics to be treated as if they
were virtual functions of a nominal class object. That is how they
work in Smalltalk. The ability to override a "static" function has
been found very useful in that language.

To put it another way, "static" to me doesn't mean, "No vtable",
especially not in conjunction with "virtual". It means we don't
need an instance. Dynamic dispatch could and should still work. In
effect we pass the vtable instead of "this".

-- Dave Harris, Nottingham, UK

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: rlankine@hotmail.com ("Risto Lankinen")
Date: Fri, 26 Sep 2003 17:30:10 +0000 (UTC)
Raw View
"Steve Folly" <ng@spfweb.co.uk> wrote in message
news:BB97B2C1.3CA87%ng@spfweb.co.uk...
> On 23/9/03 7:54 pm, in article 1064323094.157945@master.nyc.kbcfp.com,
> "Hyman Rosen" <hyrosen@mail.com> wrote:
>
> > In the obvious implementation, static virtual methods get a vtable slot,
> > and invoking the method through an object is done by dispatching on the
> > type of the object, but the methods are not passed a 'this' pointer.
>
> This implies a flag of some kind in the vtable to indicate whether or not
to
> pass a 'this' pointer for the particular method.

Uh?????  Why can't it use the class declaration which
it will need anyway to know which *other* [than 'this']
arguments shall be passed?  Deciding what to pass to
a function call is not a run-time activity, so I don't see
why vtable structures would need to be modified.

It seems to me that all that really is needed is one extra
bit in the metadata record the compiler uses internally
during compile-time to memorize the function's binary
interface.

 - Risto -


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: pasa@lib.hu ("Balog Pal")
Date: Fri, 26 Sep 2003 17:31:24 +0000 (UTC)
Raw View
"Steve Folly" <ng@spfweb.co.uk> wrote in message
news:BB97B2C1.3CA87%ng@spfweb.co.uk...

> > In the obvious implementation, static virtual methods get a vtable slot,
> > and invoking the method through an object is done by dispatching on the
> > type of the object, but the methods are not passed a 'this' pointer.
>
> This implies a flag of some kind in the vtable to indicate whether or not
to
> pass a 'this' pointer for the particular method.

The compiler very well knows the function signature at compile time,
including the hidden 'this' parameter if a function has one.  It needs no
help from the vtable. vtable is only needed to pick up the address of the
function if late-binding is used.

> If this is added,  I would imagine quite a lot of already-compiled-code
> would break when linked with new code? (If not all of it!)  Which, I think
> you'd agree is one good reason NOT to introduce them.

This change has absolutely no impact on the existing good code, source or
compiled, it merely makes a previously not allowed combination to be
well-formed, and working.

And it's almost trivial to implement IMHO.

Paul


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: hyrosen@mail.com (Hyman Rosen)
Date: Fri, 26 Sep 2003 17:31:59 +0000 (UTC)
Raw View
Steve Folly wrote:
> This implies a flag of some kind in the vtable to indicate whether or not to
> pass a 'this' pointer for the particular method.

Of course it does no such thing. The compiler has the class
definition, so it knows whether the method is a regular virtual
or a static virtual. After all, the vtable generally doesn't carry
a description of any method parameters!

> If this is added,  I would imagine quite a lot of already-compiled-code
> would break when linked with new code? (If not all of it!)  Which, I think
> you'd agree is one good reason NOT to introduce them.

No, nothing breaks. Your imagination is wrong. I do not agree.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: Richard_Damon@hotmail.com (Richard Damon)
Date: Fri, 26 Sep 2003 17:33:17 +0000 (UTC)
Raw View
ng@spfweb.co.uk (Steve Folly) wrote:

>On 23/9/03 7:54 pm, in article 1064323094.157945@master.nyc.kbcfp.com,
>"Hyman Rosen" <hyrosen@mail.com> wrote:
>
>> In the obvious implementation, static virtual methods get a vtable slot,
>> and invoking the method through an object is done by dispatching on the
>> type of the object, but the methods are not passed a 'this' pointer.
>
>This implies a flag of some kind in the vtable to indicate whether or not to
>pass a 'this' pointer for the particular method.
>
The compiler already needs to keep track of the prototype for each entry in the
vtable, why is an extra bit here to indicate "static" significant. There is no
need for a flag in the object code for the vtable.

>If this is added,  I would imagine quite a lot of already-compiled-code
>would break when linked with new code? (If not all of it!)  Which, I think
>you'd agree is one good reason NOT to introduce them.

--
richard_damon@iname.com (Redirector to my current best Mailbox)
rdamon@beltronicsInspection.com (Work Adddress)
Richad_Damon@msn.com (Just for Fun)

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: Richard_Damon@hotmail.com (Richard Damon)
Date: Fri, 26 Sep 2003 17:33:21 +0000 (UTC)
Raw View
anonimo@terra.es ("Juan") wrote:

>
>"Francis Glassborow" <francis@robinton.demon.co.uk> escribi=F3 en el men=
saje
>news:oE6$1oF76Bc$EwwU@robinton.demon.co.uk...
>>
>> And my understanding is that a.callStatic() is entirely synonymous (i.=
e.
>> completely interchangeable) with A::callStatic() and as such there is =
no
>> case where the former syntax is required.
>>
>I don't understand why this syntax is allowed. It's unnecesary and obscu=
res
>the code because the reader can think that callStatic does something wit=
h a.
>
The purpose is to get the type of a variable, so even if the variable cha=
nges
you still get the correct function. This is also very usefully in templat=
e code.
Being able to extend this second to look at the run-time type not just th=
e
static type is the whole basis of this proposal.


--=20
richard_damon@iname.com (Redirector to my current best Mailbox)
rdamon@beltronicsInspection.com (Work Adddress)
Richad_Damon@msn.com (Just for Fun)

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: hyrosen@mail.com (Hyman Rosen)
Date: Fri, 26 Sep 2003 18:07:24 +0000 (UTC)
Raw View
Dave Harris wrote:
> So calling other virtual statics doesn't work?
Right.

> Dynamic dispatch could and should still work. In
> effect we pass the vtable instead of "this".

I hadn't thought of it in that way. I suppose you're
right. OK, I'm against virtual statics :-)

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: richard_damon@iname.com ("RCN")
Date: Mon, 29 Sep 2003 05:09:36 +0000 (UTC)
Raw View
"Dave Harris" <brangdon@cix.co.uk> wrote in message
news:memo.20030925201208.61199B@brangdon.madasafish.com...
> hyrosen@mail.com (Hyman Rosen) wrote (abridged):
> > In the obvious implementation, static virtual methods get a vtable
> > slot, and invoking the method through an object is done by
> > dispatching on the type of the object, but the methods are not
> > passed a 'this' pointer.
>
> So calling other virtual statics doesn't work?
>
>     struct Base {
>         virtual static int func() { return func2(); }
>         virtual static int func2() { return 1; }
>     };
>
>     struct Derived : Base {
>         virtual static int func2() { return 2; }
>     };
>
>     void test() {
>         Derived d;
>         Base &b = d;
>         cout << b.func();
>     }
>
> If this doesn't output "2", then "virtual" is meaning something
> strange. I was expecting virtual statics to be treated as if they
> were virtual functions of a nominal class object. That is how they
> work in Smalltalk. The ability to override a "static" function has
> been found very useful in that language.
>
> To put it another way, "static" to me doesn't mean, "No vtable",
> especially not in conjunction with "virtual". It means we don't
> need an instance. Dynamic dispatch could and should still work. In
> effect we pass the vtable instead of "this".

I would expect your example to print 1, and here is why:

when static function is call with syntax Type::fun() then the function
called is the function for the specified Type, the virtual modifier can have
no effect on this, as there is no object to apply to. When called with
syntax var.fun() then the function called depends on the type of var. With
the virtual modifier we mean to look at the dymanic, run time type, not the
static type.

One other feature in C++ is that static member function have the same
signature as free functions so that given:

int freefun(int)
and
class foo {
static int staticfun(int);
};

int func( int (*)(int))
can be passed either freefun or staticfun. Currently virtual has no affect
on the signature of a function (pointer to member must be smart enough to
call the virtual function), so it would be surprising and cause
compatibility problems to change this for static functions. This says that
static functions should NOT be passed an argument for the type of the
variable used to invoke them virtually. Yes, this says if you want to
remember the type, like your example presuposes, that func should not be
static so it has a this to allow it to dispatch to the right func2. I would
think that you would also want to write func as

virtual int func() { return this->func2(); }

if you want to dispatch on the type of the variable, thus reserving  {
return func2(); } for the statically bound version. (It could be argued
alternatively that you should need to write:

virtual int func() { return Base::func2(); }

if you want staticly binding. I am not sure which is less surprising.

Richard


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: belvis@pacbell.net (Bob Bell)
Date: Mon, 29 Sep 2003 05:12:27 +0000 (UTC)
Raw View
hyrosen@mail.com (Hyman Rosen) wrote in message news:<1064323094.157945@master.nyc.kbcfp.com>...
> Shantanu Garg wrote:
>  > Second type of syntax is never needed because the effect produced
>  > by the second syntax can be achieved by even making it non-static.
>
> But then you prevent the first use, don't you?
>
> Static virtuals would be used for methods which depend upon class
> but not upon individual objects. It's so blindingly simple to many
> of us that the "why do you need it?" questions are just maddening.

It may be maddening, but part of the point of asking "why do you need
it?" is to find out how difficult it is to get the effect you want. In
this case, the effect you want is just not very difficult with
existing language features.

The standard committee has limited resources, so it _must_ consider
proposals this way.

> Clearly they're not "needed" in an absolute sense, because as has
> been said many times, you can do the same with a static/virtual pair
> of methods, but that's just a substitute for what is really wanted.

So what? If they're not "needed" (i.e., there is a workaround that
isn't too onerous), why should the standard committee go to the
(considerable) trouble of making this change?

I would rather have the standard committee spend its time on changes
where the current workarounds _are_ onerous or even non-existent, e.g.
type_of, type traits, etc.

Bob

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: brangdon@cix.co.uk (Dave Harris)
Date: Mon, 29 Sep 2003 15:40:48 +0000 (UTC)
Raw View
richard_damon@iname.com ("RCN") wrote (abridged):
> >     struct Base {
> >         virtual static int func() { return func2(); }
> >         virtual static int func2() { return 1; }
> >     };
> >
> >     struct Derived : Base {
> >         virtual static int func2() { return 2; }
> >     };
>
> I would expect your example to print 1, and here is why:
>
> [...]
> One other feature in C++ is that static member function have the
> same signature as free functions so that given:
>
> int freefun(int)
> and
> class foo {
> static int staticfun(int);
> };
>
> int func( int (*)(int))
> can be passed either freefun or staticfun. Currently virtual has
> no affect on the signature of a function (pointer to member must
> be smart enough to call the virtual function), so it would be
> surprising and cause compatibility problems to change this for
> static functions.

I agree we shouldn't add overhead to pointers to non-virtual static
functions. However, I think it's reasonable for pointers to
virtual static functions to have a different type to pointers to
non-virtual static functions. It can't cause compatibility problems
because there are no existing virtual static functions to be
compatible with.

It may be surprising, but in my view it is also surprising if a call
to a virtual static like the one in func() is not dispatched
dynamically. It seems to contradict what the word "virtual" means.

Which is more surprising? That is probably a question for the people
who teach C++ to newcomers. I am not a teacher. Frankly, I wouldn't
want to have to teach either variant. It just seems like another
tricky mess for students to wrap their minds around.

-- Dave Harris, Nottingham, UK

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: pasa@lib.hu ("Balog Pal")
Date: Mon, 29 Sep 2003 17:10:02 +0000 (UTC)
Raw View
"Dave Harris" <brangdon@cix.co.uk> wrote in message
news:memo.20030925201208.61199B@brangdon.madasafish.com...

> So calling other virtual statics doesn't work?
>
>     struct Base {
>         virtual static int func() { return func2(); }
>         virtual static int func2() { return 1; }
>     };

> If this doesn't output "2", then "virtual" is meaning something
> strange.

It would always call Base::func2(); printing 1.

IMHO that is a restriction we could pretty well live with. Especially if a
good quality compiler would issue a warning.

A static function can't touch an instance, so it can't use:
- nonstatic data members
- nonstatic member functions
- virtual functions (in a virtual way -- through this)

To fix the situation we could:

1. just live with the fact you'll get a nonvirtual call, the programmer will
learn the rule -- as he does currently if a virtual function is called in
ctor or dtor.

2. not allow calling virtual functions from a static function at all [safe,
but reintroduces an artificial restriction again]

3. forbid calling virtual functions using the 'lazy' syntax.   IOW restrict
the syntax to not work if you write func2(); but do work if you write
Base::func2().   [that would produce more expressive code and putting
compatibility aside would be good for ctors and dtors too;   I guess
restrictions on syntax with ovtaining a pointer-to-member were introduced
along similar reasons]

> To put it another way, "static" to me doesn't mean, "No vtable",
> especially not in conjunction with "virtual".

Technically it could be covered even working your way.  But that would need
the compiler passing a hidden vtable pointer.  The implementation is no
longer on the 'trivial' level, but it's still not really hard.  But IMHO
costy enough to gain NO votes.   As a side effect you lose
interchangability --  a pointer to such function is no longer compatible
with a pointer to a regular function as is happens with a static function.
Nor is it compatible with a pointr-to-member-function.

Paul


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: Richard_Damon@hotmail.com (Richard Damon)
Date: Tue, 30 Sep 2003 17:45:28 +0000 (UTC)
Raw View
brangdon@cix.co.uk (Dave Harris) wrote:
...
>I agree we shouldn't add overhead to pointers to non-virtual static
>functions. However, I think it's reasonable for pointers to
>virtual static functions to have a different type to pointers to
>non-virtual static functions. It can't cause compatibility problems
>because there are no existing virtual static functions to be
>compatible with.
>
>It may be surprising, but in my view it is also surprising if a call
>to a virtual static like the one in func() is not dispatched
>dynamically. It seems to contradict what the word "virtual" means.
>
>Which is more surprising? That is probably a question for the people
>who teach C++ to newcomers. I am not a teacher. Frankly, I wouldn't
>want to have to teach either variant. It just seems like another
>tricky mess for students to wrap their minds around.
>
>-- Dave Harris, Nottingham, UK
>


In the non-static case, adding virtual does not change the signature of a
function, I would not like to see that changed in the static case, that would
cause surprises to me.

I will repeat, I would be surprised if the virtual static call in func() was
dispatched on the type of some remote object. The definition of virtual static
was that it used dispatch WHEN CALL ON AN OBJECT with the obj.fun() or
obj->fun() notation. Inside func() there is no object specified or even
assumable as we do not have a "this" in scope. To make them dispatch we need to
either give them a "this" (in which case they are NOT static) or we need to
create some new context between static and non-static.

I can see great potential for confusion if virtual static func() calls virtual
static func2() and gets dispatch, what if virtual static func() calls
(non-virtual) static func1() which calls virtual static func2(), should we get
dispatch? (this would require extraordinary behind the scenes machinery). If not
the dispatch condition is very fragile and subject to details far from the code
in question (the file where the class definition occurs is often in a header
file while the body is often in a separate code file).

I don't see this as that confusing to teach. The rule is that if called on an
object (explicitly with obj.func(), or objp->func() or through an implied "this"
in a NON-static function, which are the only ones with a "this") you get dynamic
dispatching. Without an object you get static dispatching, which is all that is
available. It actually seems less complicated then teaching the idiom needed to
get around this lack of virtual static.
--
richard_damon@iname.com (Redirector to my current best Mailbox)
rdamon@beltronicsInspection.com (Work Adddress)
Richad_Damon@msn.com (Just for Fun)

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: dsp@bdal.de (Daniel Spangenberg)
Date: Fri, 12 Sep 2003 23:01:52 +0000 (UTC)
Raw View
Hello,

Since many contributions concentrate on the same points, I will
give one single answer and hopefully will not forget the individual
questions though they are of general interest. I read all your contributi=
ons
and I hope that you forgive me that "uniform" answer.

My argumentation concerning the advantages of static virtual
functions can be divided into several stages of complexity.

1) The most simplest pro argument is just a matter of convenience.
This directly applies to the anwers of Andrew Koenig (and I hope, the
example is short enough)

Consider the following (pseudo-) C++ code:

#include <string>

struct Base
{
  virtual static std::string name() { return "Base"; } // This is one of =
the
most common examples..
};

struct Derived : Base
{
  virtual static std::string name() { return "Derived"; } // This is one =
of
the most common examples..
};

void foo(const Base& b)
{
  b.name(); // Calls polymorphic version
  b.Base::name(); // Calls static version
  Base::name(); // Also calls static version
}

int main()
{
  Base b;
  foo(b);
}

Many may argue (and did, like llewelly), that the same effect can be reac=
hed
by means of simple virtual functions and simple static functions. This is=
 the

workaround we need for the same aim (Hyman Rosen and Risto Lankinen
were aware of this situation, Lo=EFc had a similar problem and solved it =
as
below):

#include <string>

struct Base
{
  static std::string sname() { return "Base"; } // This is one of the mos=
t
common examples..
  virtual std::string name() const { return sname(); }
};

struct Derived : Base
{
  static std::string sname() { return "Derived"; }
  virtual std::string name() const { return sname(); }
};

void foo(const Base& b)
{
  b.name(); // Calls polymorphic version
  b.Base::name(); // Calls static version
  Base::sname(); // Also calls static version but with different name...
}

The disadvantage is: We need always two functions per class, where actual=
ly
only one is needed. To my opinion this an unnecessary uglyness.

Static functions are the right place to provide non-individual operations
and/or
data, but sometimes we need polymorphic access to the **actual** class
which provides its class specific data or behaviour.

You may argue that "because it can be solved by current means of the
language,
we don't need this feature" (Hello llewelly!). This is not enough (to my
opinion),
because we can think of several existing features of the language, which =
are
actually not "necessary", e.g. covariant return types of virtual function=
s.

2) The next argumentation is a view in a possible future direction of C++=
 and

thus is more controversial than the first point. It is a direct answer of
Dietmar's
contribution who very well recognized where the wind blows from ;-))

C++ does (currently) not have the idea of metaclasses. But iff these woul=
d be

introduced, virtual static function would be a very elegant add-on for th=
em.

To exemplify that, I use a currently not accepted "metaclass" keyword and
will
not discuss whether the hereto used syntax is nice or not (This would be =
the
point of another discussion). Lets assume, that we have the first mention=
ed
Base/Derived classes available at the following point:

#include <iostream>
#include <ostream>

typedef metaclass Base MyBaseMetaClass;

void bar()
{
  MyBaseMetaClass m =3D Derived; // The literals of metaclasses are class
names!
  std::cout << m.name() << std::endl;
}


// This would also be discussable under these ideas: Use real **virtual**
c'tors:
struct Fruit
{
  virtual Fruit(); // Nice, a virtual c'tor (currently not allowed)

  virtual ~Fruit(){}
};

struct Mellon : Fruit
{
  virtual Mellon(); // Some thing
};

Fruit* gee(const metaclass Fruit& f)
{
  Fruit* pF =3D new f; // Construct some unknown fruit
  return pF;
}

void do()
{
  const metaclass fr =3D Mellon; // Chose a fruit
  Fruit* p =3D gee(fr); // Lets make a mellon
  delete p;
}

To summarize: While the second argumentation concerning future
directions of C++ and its applyability (Does this word exist? Please forg=
ive
my language fantasies...) under those situations is of lower importance,
the very simple consistency and usability of virtual static functions und=
er
normal conditions (1st example) show clearly its advantages. Maybe these
advantages are not too great, but I think at least as great as several ot=
her
existing language items.

Thanks for listeneing and many Greetings from Bremen,

Daniel



---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: ng@spfweb.co.uk (Steve Folly)
Date: Fri, 12 Sep 2003 23:03:40 +0000 (UTC)
Raw View
On 12/9/03 10:14 am, in article hTe8b.2218$g4.46267@news2.nokia.com, ""Risto
Lankinen"" <rlankine@hotmail.com> wrote:

> Sometimes a method is needed which returns information
> that is purely class-dependent, such as shown below:
>
> struct S
> {
>  static virtual size_t footprint() const { return sizeof(S); }
> };

Right, so then it's just static since it doesn't depend on an object of type
S.

> This function should be virtual because the derivants of the
> class must return a different value that correctly reflects their
> different characteristics.

So then you define a static footprint() method in each of the derivations.

> Using sizeof(S) in the calling site
> is not possible, since some derivants will augment the result
> with whatever extra payload they may have (e.g. footprint
> of a handle class is the size of the handle class PLUS the
> footprint of the implementation class, with perhaps minus
> the size of the pimpl pointer itself).

But you wouldn't be using the base class's footprint() method, you'd be
using the derivation's footprint() method.

> But this function also should be static

No argument here :)

> because sometimes
> there is no instance of 'S' (or its derivant) available when
> the footprint of an object is needed.  Depending on how
> the derived class is coded, it may not even be possible to
> instantiate such an object (e.g. it may contain pure virtual
> methods, have a private constructor, produce unwanted
> side effects if instantiated, exhaust a resource if it's a RAII
> class, or just be prohibitively inefficient to instantiate).

Exactly. That's what static methods are useful for - you can call them
without an instance of the class.

>
> Without static virtuals one would have to do the following
> ugliness...
>
> ((Derived *)0)->footprint();
>

Isn't that rather dangerous? Don't most (all?[1]) compiler implementations
add an extra vtable pointer with the object's data so it knows where to look
up virtual methods?

> .... to find out the size.  With static virtuals the call would
> look like this...
>
> Derived::footprint();
>
> .... which is clearly better.
>

But then you're just back to a normal static method?

> Cheers!
>
> - Risto -
>
>


Sorry, I may be missing the point but from what you've described I still
can't see how static methods can be virtual.


[1] - feel free to correct me here!

--
Regards,
Steve

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: pasa@lib.hu ("Balog Pal")
Date: Mon, 15 Sep 2003 17:10:20 +0000 (UTC)
Raw View
"Andrew Koenig" <ark@acm.org> wrote in message
news:yu99r82rp1cy.fsf@tinker.research.att.com...

> Please give an example of such a real-world programming problem.
> The shorter and more convincing the example is, the better.

I too have a few cases where I could use such a beast. Some of my classes
return constants. Like sizeof(*this), count of some internal elements, etc.
Currently I have static and a virtual doing that, one calling the other. Not
exactly nice.

A possible static virtual function would work as following:

struct FieldDesc;
struct RecordBase
{
    virtual static string GetTableName() const;
    virtual static int GetFieldCount() const
    {
    // definition is like for a static function. this can't be used,
    // neither any nonstatic members
        return 0; // no fields
    }
    // idx in range [0 to GetFieldCount() )
    static virtual struct FieldDesc const & GetFieldDesc(int idx) const;
};

struct CustomersPk : RecordBase
{
    typedef RecordBase tParent;
    static const int myfields = 1;
    static FieldDesc fields[myfields];

    virtual static string GetTableName() const
    {
        return "CUSTOMER";
    }
    virtual static int GetFieldCount() const
    {
        // adds fields: CUST_ID
        tParent::GetFieldCount() + myfields;
    }
    static virtual struct FieldDesc const & GetFieldDesc(int idx) const
    {
        return fields[idx];
    }
};
struct Customers : CustomersPk
{
    // adds fields: CUST_NAME CUST_ADDRESS
    static const int myfields = 2;
    static FieldDesc fields[myfields];

    typedef RecordBase CustomersPk;
    virtual static int GetFieldCount() const
    {
        tParent::GetFieldCount() + myfields;
    }
    // actually this is the 'common' impl.
    static virtual struct FieldDesc const & GetFieldDesc(int idx) const
    {
        if(idx < tParent::GetFieldCount())
            return tParent::GetFieldDesc(int idx);
        else
            return fields[idx - tParent::GetFieldDesc(int idx)];
    }
};

//usage:
void func(const CustomersPk & rec)
{
    Customers::GetFieldCount(); // that works also, returns 3
    rec.GetFieldCount(); // call based on dynamic type, returns 1 or 3
}

Actually I find in most hierarchies you can find similar data that can be
fetched from a static function, but also is useful in a polymorphic way.
Like advanced type info, reliable class name, class id, sizeof(*this)...

Paul





---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: shantanu_garg@mentor.com ("Shantanu Garg")
Date: Fri, 19 Sep 2003 13:59:05 +0000 (UTC)
Raw View
Daniel Spangenberg wrote:
>
> To summarize: While the second argumentation concerning future
> directions of C++ and its applyability (Does this word exist? Please
> forgive my language fantasies...) under those situations is of lower
> importance,
> the very simple consistency and usability of virtual static functions
> under normal conditions (1st example) show clearly its advantages.
> Maybe these advantages are not too great, but I think at least as
> great as several other existing language items.
>

One point about which we are discussing is that whether we want that feature
or not. We should also think about why this feature was not provided in the
previous standards of c++. I think it was an overlook from the standard
point of view because anyway we are providing this feature with 'delete' in
some other form. Around 5-6 months back I have had a discussion in
"comp.c++.moderated" for providing this feature in Standard c++ and even
that point of time no concrete answers were given
(http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&frame=right&th=
a398e5754769dfd3&seekm=3E2C01F7.305FBB5C%40bdal.de#link1).

    I can give you one example where this can be useful. There are some
places where we don't have dynamic type information of an object say when we
are calling a function and passing the pointer. If inside that function we
want to call some function polymorphically which is not bound to any object
but to the type of the object, we cannot do that.

class A
{     virtual static int GetAccessCount() { static int i = 0; return
        };

class B : public A
{    virtual static int GetAccessCount() { static int i = 0; return
        };

void func(A* a) {  std::cout<<a->GetAccessCount(); }
int main()
{
    A* a = NULL:
    //some logic goes here for assigning 'a' with dynamic type.
    ...
    func(a);
    return 0;
}

Here we want to keep track of which class is winning all the time.
This example may not be very concrete but it can help us in undersatnding
the need of "virtual static".

-Shantanu

> Thanks for listeneing and many Greetings from Bremen,
>
> Daniel
>
>
>
> ---
> [ comp.std.c++ is moderated.  To submit articles, try just posting
> with ] [ your news-reader.  If that fails, use
> mailto:std-c++@ncar.ucar.edu    ] [              --- Please see the
> FAQ before posting. ---               ] [ FAQ:
> http://www.jamesd.demon.co.uk/csc/faq.html                       ]


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: francis@robinton.demon.co.uk (Francis Glassborow)
Date: Sat, 20 Sep 2003 16:49:37 +0000 (UTC)
Raw View
In article <bkeqkg$11jp1$1@ID-90849.news.uni-berlin.de>, Shantanu Garg
<shantanu_garg@mentor.com> writes
>class A
>{     virtual static int GetAccessCount() { static int i = 0; return
>        };
>
>class B : public A
>{    virtual static int GetAccessCount() { static int i = 0; return
>        };
>
>void func(A* a) {  std::cout<<a->GetAccessCount(); }
>int main()
>{
>    A* a = NULL:
>    //some logic goes here for assigning 'a' with dynamic type.
>    ...
>    func(a);
>    return 0;
>}
>
>Here we want to keep track of which class is winning all the time.
>This example may not be very concrete but it can help us in undersatnding
>the need of "virtual static".

Make the counters static data for the class and the access functions
ordinary virtual member functions and the problem goes away. I have
still to see a persuasive example of why a virtual static member would
be worth the cost of change.


--
Francis Glassborow      ACCU
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: shantanu_garg@mentor.com ("Shantanu Garg")
Date: Tue, 23 Sep 2003 04:48:11 +0000 (UTC)
Raw View
Francis Glassborow wrote:
> In article <bkeqkg$11jp1$1@ID-90849.news.uni-berlin.de>, Shantanu Garg
> <shantanu_garg@mentor.com> writes
>> Here we want to keep track of which class is winning all the time.
>> This example may not be very concrete but it can help us in
>> undersatnding the need of "virtual static".
>
> Make the counters static data for the class and the access functions
> ordinary virtual member functions and the problem goes away. I have
> still to see a persuasive example of why a virtual static member would
> be worth the cost of change.

After giving some thought to it, here is my understanding -

           Static member functions can be called using two type of syntax in
C++. One is 'A::callStatic()' and other is 'a.callStatic()'. First syntax is
used when we don't have any object with us and we want to call static
method. I don't see any use of second syntax. Second type of syntax is never
needed because the effect produced by the second syntax can be achieved by
even making it non-static. If we can find an example which proves the need
of the second syntax then the same example can be extended to prove why
virtual static is needed.



-Shantanu



---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: francis@robinton.demon.co.uk (Francis Glassborow)
Date: Tue, 23 Sep 2003 18:54:33 +0000 (UTC)
Raw View
In article <bkkba7$2j7cb$1@ID-90849.news.uni-berlin.de>, Shantanu Garg
<shantanu_garg@mentor.com> writes
>           Static member functions can be called using two type of syntax in
>C++. One is 'A::callStatic()' and other is 'a.callStatic()'. First syntax is
>used when we don't have any object with us and we want to call static
>method. I don't see any use of second syntax. Second type of syntax is never
>needed because the effect produced by the second syntax can be achieved by
>even making it non-static. If we can find an example which proves the need
>of the second syntax then the same example can be extended to prove why
>virtual static is needed.

And my understanding is that a.callStatic() is entirely synonymous (i.e.
completely interchangeable) with A::callStatic() and as such there is no
case where the former syntax is required.

--
Francis Glassborow      ACCU
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: johnchx2@yahoo.com (johnchx)
Date: Tue, 23 Sep 2003 18:54:40 +0000 (UTC)
Raw View
shantanu_garg@mentor.com ("Shantanu Garg") wrote
> After giving some thought to it, here is my understanding -
>
>            Static member functions can be called using two type of syntax in
> C++. One is 'A::callStatic()' and other is 'a.callStatic()'. First syntax is
> used when we don't have any object with us and we want to call static
> method. I don't see any use of second syntax. Second type of syntax is never
> needed because the effect produced by the second syntax can be achieved by
> even making it non-static. If we can find an example which proves the need
> of the second syntax then the same example can be extended to prove why
> virtual static is needed.

I don't agree.

Being able to use the "ordinary" member function call syntax to invoke
a static member function can be useful in template programming.  For
instance:

   struct A {
      A( int i ): mVal( i ) {}
      int bar() const { return mVal; }
      int mVal;
   };

   struct B {
      static int bar() { return 5; }
   };

   template < class T >
   int foo( const T& t ) {
      return t.bar();      // works for static & non-static bar()
   }

   int main() {
      A fa ( 10 );
      B fb;
      foo(fa);
      foo(fb);
   }

I don't see any relationship between this usage and the hypothetical
virtual static member functions.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: hyrosen@mail.com (Hyman Rosen)
Date: Tue, 23 Sep 2003 18:54:57 +0000 (UTC)
Raw View
Shantanu Garg wrote:
 > Second type of syntax is never needed because the effect produced
 > by the second syntax can be achieved by even making it non-static.

But then you prevent the first use, don't you?

Static virtuals would be used for methods which depend upon class
but not upon individual objects. It's so blindingly simple to many
of us that the "why do you need it?" questions are just maddening.

Clearly they're not "needed" in an absolute sense, because as has
been said many times, you can do the same with a static/virtual pair
of methods, but that's just a substitute for what is really wanted.

This is what needs to be done now:

struct A {
     static std::string stype() { return "A"; }
     virtual std::string type() const { return stype(); } // noise
};
struct B : A {
     static std::string stype() { return "B"; }
     virtual std::string type() const { return stype(); } // noise
};

void f(const A &a, const A &b)
{ std::cout << a.type() << b.type(); }

int main()
{
   std::cout << A::stype() << B::stype(); // print AB
   f(A(), B()); // print AB
}

We would like to be able to say

struct A { static virtual std::string type() { return "A"; } };
struct B : A { static virtual std::string type() { return "B"; } };

void f(const A &a, const A &b)
{ std::cout << a.type() << b.type(); }  // dispatching calls

int main()
{
   std::cout << A::type() << B::type(); // print AB, non-dispatching calls
   f(A(), B()); // print AB
}

In the obvious implementation, static virtual methods get a vtable slot,
and invoking the method through an object is done by dispatching on the
type of the object, but the methods are not passed a 'this' pointer.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: dietmar_kuehl@yahoo.com (Dietmar Kuehl)
Date: Tue, 9 Sep 2003 11:38:24 +0000 (UTC)
Raw View
dsp@bdal.de (Daniel Spangenberg) wrote:
> I would like to (newly) discuss the request for this very
> feature, which is currently missing in the standard C++
> language.

It may be arguable that C++ would benefit from some form of class objects.
However, I don't see any point in a singular extension providing virtual
static functions, especially, as it is neither clear what use they have nor
how the virtually is supposed to enter the game.

> It brought my attention to the fact,
> that at least one point in the current standard C++ language
> behaves as if there is a virtual static function in action, namely
> the user-defined class deallocation functions of the scalar delete
> family in case of a class hierarchy which bases on virtual destructors.

Although this is described a static function, it is actually non-static one:
the function called depends on the dynamic type of the object being deleted.
It is considered to be a static function because it does not have any means
of access to the object's state - the object has just been destroyed when
this function is called.

> Now, since compiler writers already have to solve such a problem in
> current implementations it seems natural for me to ask for their general
> existence for normal users of the language (aka "programmers").

Maybe my imagination is somewhat limited but maybe you can help me out:
- How is the dynamic function determined which called within a static call?
- What is it good for?
--
<mailto:dietmar_kuehl@yahoo.com> <http://www.dietmar-kuehl.de/>
Phaidros eaSE - Easy Software Engineering: <http://www.phaidros.com/>

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: llewelly.at@xmission.dot.com (llewelly)
Date: Tue, 9 Sep 2003 11:38:46 +0000 (UTC)
Raw View
dsp@bdal.de (Daniel Spangenberg) writes:

> Hello,
>
> I would like to (newly) discuss the request for this very
> feature, which is currently missing in the standard C++
> language.
>
> When I began using C++ in 1998, I was used to the existence
> of Object Pascals (aka Delphi) "class functions" and (naturally)
> expected there existence in a rich language such like C++.

[snip a lot of wandering text asking for polymorphic classwide
    functions.]

> The reason for this very question is not an academic one. Its origin
> bases on real-world programming problems which naturally would be
> solved by means of virtual static functions. So I would like to start
> this
> thread as begin of a constructive dicussion concerning this language
> extension .
[snip]

I would like to see a comparision of your suggested feature with an
    attempt to emulate it with ordinary virtual member functions.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: ark@acm.org (Andrew Koenig)
Date: Thu, 11 Sep 2003 16:32:25 +0000 (UTC)
Raw View
Daniel> I would like to (newly) discuss the request for this very
Daniel> feature, which is currently missing in the standard C++
Daniel> language.

<snip>

Daniel> The reason for this very question is not an academic one. Its
Daniel> origin bases on real-world programming problems which
Daniel> naturally would be solved by means of virtual static
Daniel> functions. So I would like to start this thread as begin of a
Daniel> constructive dicussion concerning this language extension.

Please give an example of such a real-world programming problem.
The shorter and more convincing the example is, the better.

--
Andrew Koenig, ark@acm.org

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: johnchx2@yahoo.com (johnchx)
Date: Thu, 11 Sep 2003 16:33:00 +0000 (UTC)
Raw View
dsp@bdal.de (Daniel Spangenberg) wrote

> My rebellious mind reminded me again after reading Stephen
> Dewhurst's last Gotcha book. It brought my attention to the fact,
> that at least one point in the current standard C++ language
> behaves as if there is a virtual static function in action, namely
> the user-defined class deallocation functions of the scalar delete
> family in case of a class hierarchy which bases on virtual destructors.

But a deallocation function is always called to deallocate a
*particular* object, while a general-purpose static member is called
with no object in particular (i.e. no this pointer).  So what object's
dynamic type should be consulted in dispatching the call to a "virtual
static" member?

Am I missing something obvious?

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: hyrosen@mail.com (Hyman Rosen)
Date: Fri, 12 Sep 2003 09:10:31 +0000 (UTC)
Raw View
Dietmar Kuehl wrote:
> - How is the dynamic function determined which called within a static call?

By the (required) object through which it's invoked.

> - What is it good for?

Not much, except that the 'this' pointer doesn't need to be passed.

This is the equivalent in standard C++:

struct A { static void f_s() { } virtual void f() { f_s(); } };
struct B : A { static void f_s() { } void f() { f_s(); } };
A *p = new B; p->f(); // eventually calls B::f_s

The OP would like to avoid the repetitive forwards of f to f_s and write

struct A { virtual static void f() { } };
struct B : A { static void f() { } };
A *p = new B; p->f(); // calls B::f

And yes, I know that you could just put the code in the (non-static)
virtuals, but static virtual emphasizes that the functions are classwide,
not per-object. It's just one of those things that seems like it ought to
be there and has a trivial implementation.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: loic.actarus.joly@wanadoo.fr (=?ISO-8859-1?Q?Lo=EFc_Joly?=)
Date: Fri, 12 Sep 2003 09:13:33 +0000 (UTC)
Raw View
Andrew Koenig wrote:
> Please give an example of such a real-world programming problem.
> The shorter and more convincing the example is, the better.

I had once uppon a time a situation where I believed I required a=20
virtual static function.

It was for serialisation :
- When writing to a file, I needed a virtual function that returned a=20
class Id to be written to the file
- When reading from a file, I needed a static function that could give=20
me the Id of each class, so I could know without using existing object=20
what was the type of the object to be read.

I solved this problem by using two functions, one static and the other=20
one virtual, each returning the same value.

--=20
Lo=EFc

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: rlankine@hotmail.com ("Risto Lankinen")
Date: Fri, 12 Sep 2003 09:14:41 +0000 (UTC)
Raw View
Hi!

"Andrew Koenig" <ark@acm.org> wrote in message
news:yu99r82rp1cy.fsf@tinker.research.att.com...
> Daniel> I would like to (newly) discuss the request for this very
> Daniel> feature, which is currently missing in the standard C++
> Daniel> language.
>
> Please give an example of such a real-world programming problem.
> The shorter and more convincing the example is, the better.

Sometimes a method is needed which returns information
that is purely class-dependent, such as shown below:

struct S
{
   static virtual size_t footprint() const { return sizeof(S); }
};

This function should be virtual because the derivants of the
class must return a different value that correctly reflects their
different characteristics.  Using sizeof(S) in the calling site
is not possible, since some derivants will augment the result
with whatever extra payload they may have (e.g. footprint
of a handle class is the size of the handle class PLUS the
footprint of the implementation class, with perhaps minus
the size of the pimpl pointer itself).

But this function also should be static, because sometimes
there is no instance of 'S' (or its derivant) available when
the footprint of an object is needed.  Depending on how
the derived class is coded, it may not even be possible to
instantiate such an object (e.g. it may contain pure virtual
methods, have a private constructor, produce unwanted
side effects if instantiated, exhaust a resource if it's a RAII
class, or just be prohibitively inefficient to instantiate).

Without static virtuals one would have to do the following
ugliness...

((Derived *)0)->footprint();

.... to find out the size.  With static virtuals the call would
look like this...

Derived::footprint();

.... which is clearly better.

Cheers!

 - Risto -


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]





Author: dsp@bdal.de (Daniel Spangenberg)
Date: Mon, 8 Sep 2003 08:29:23 +0000 (UTC)
Raw View
Hello,

I would like to (newly) discuss the request for this very
feature, which is currently missing in the standard C++
language.

When I began using C++ in 1998, I was used to the existence
of Object Pascals (aka Delphi) "class functions" and (naturally)
expected there existence in a rich language such like C++.

My rebellious mind reminded me again after reading Stephen
Dewhurst's last Gotcha book. It brought my attention to the fact,
that at least one point in the current standard C++ language
behaves as if there is a virtual static function in action, namely
the user-defined class deallocation functions of the scalar delete
family in case of a class hierarchy which bases on virtual destructors.

Interestingly the current Standard describes in chapter 12.5
the effect of those functions in some detail:

1) They are by definition static functions, even if not explicitely
declared as such (!)

2) If the static type of its object argument has a virtual destructor,
 the deallocation function corresponding to its **dynamic type** is
 used.

Funnily the standard directly describes this effect as equivalent to
that of a virtual static member, but in the same sentences disallows
the valid construction of such virtual statics in 12.5/p. 7:

"Since member allocation and deallocation functions are static they
cannot be virtual. [Note: however, when the cast-expression of a
delete-expression refers to an object of class type, because the
deallocation function actually called is looked up in the scope of the
class that is the dynamic type of the object, if the destructor is
virtual, the effect is the same.[..]"

Now, since compiler writers already have to solve such a problem in
current implementations it seems natural for me to ask for their general

existence for normal users of the language (aka "programmers").

The reason for this very question is not an academic one. Its origin
bases on real-world programming problems which naturally would be
solved by means of virtual static functions. So I would like to start
this
thread as begin of a constructive dicussion concerning this language
extension .

Thanks for Your contributions,

Daniel Spangenberg






---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]