home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,490 of 33,346   
   Ivan Godard to Andy Champ   
   Re: local function as default value   
   20 Jul 12 17:42:05   
   
   From: igodard@pacbell.net   
      
   On 7/20/2012 1:43 PM, Andy Champ wrote:   
   > On 20/07/2012 19:44, Ivan Godard wrote:   
   >> The following seems reasonable:   
   >>      struct S {   
   >>          int  defVal() { return 0; }   
   >>          void p(int i, int j = defVal()) {}   
   >>      };   
   >> but gets:   
   >> error: a nonstatic member reference must be relative to a   
   >>             specific object   
   >>             void p(int i, int j = defVal()) {}   
   >> and similar on other compilers. This seems odd to me: if "p" is to   
   >> be called there must be an "S" value to be "this" at the call site,   
   >> which could be used as "this" for "defVal" too. Presumably the same   
   >> would apply to a local data member used as a default as well.   
   >>   
   >> Yes, I know there's an easy workaround:   
   >>      struct S {   
   >>          int  defVal() { return 0; }   
   >>          void p(int i, int j) {}   
   >>          void p(int i) { p(defVal()); }   
   >>      };   
   >> but why is it necessary?   
   >   
   > At the time defVal() gets called you don't have an S to connect it to   
   > - what would be the value of "this" within the defVal function?   
   >   
   > (In the second case defVal gets called from within the second p(...)   
   > function and uses its "this")   
   >   
   > You could also get around it by making defVal static, so it doesn't   
   > have a "this".   
   >   
   > Andy   
   >   
   >   
   Yes, I know that's the way it's defined - but why is it defined that   
   way? The compiler knows perfectly well what "this" it will use to call   
   p, and could use that to call defVal, in effect performing my manual   
   expansion without requiring me to write the second function. There   
   should not be any implementation issues involved in making the default   
   arguments evaluate in what is in effect the scope of the function body.   
      
   Is there a practical problem with this that I've overlooked, or is it   
   just happenstance and nobody had thought of it?   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca