Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c++ - Using a class member as a default argument for a member function

Is there another way than manually overloading the corresponding member function and calling the first overload with the member as the argument?

I am trying something along the lines of

class test
{
    string t1="test";

    testfun( string& val = this->t1 )
    { /* modify val somehow */ }
};

(Test it: http://goo.gl/36p4CF)

Currently I guess there is no technical reason why this should not work.

  • Is there a solution doing it this way except overloading and setting the parameter manually?
  • Why is this not working, is there a technical reason for it?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[dcl.fct.default]/8:

The keyword this shall not be used in a default argument of a member function.

This is a special case of a general problem: You cannot refer to other parameters in a default argument of a parameter. I.e.

void f(int a, int b = a) {} 

Is ill-formed. And so would be

class A
{
    int j;
};

void f(A* this, int i = this->j) {}

Which is basically what the compiler transforms a member function of the form void f(int i = j) {} into. This originates from the fact that the order of evaluation of function arguments and the postfix-expression (which constitutes the object argument) is unspecified. [dcl.fct.default]/9:

Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...