left-hand operand of comma has no effect

Discussion in 'C++' started by s88, Sep 22, 2010.

  1. s88

    s88 Guest

    Hi all,

    I like to implement a new syntax in C++ for my work. It supposed to be
    (a,b) , which represents a+b, for example.
    My implementation as following...

    inline myClass operator () (myClass &left, myClass &right);

    the usage of this operator is
    cout << (a,b) << endl;

    However, g++ reports
    "warning: left-hand operand of comma has no effect"

    Does it mean the 'a' has no effect? How should I do?

    thanks,

    Dave
     
    s88, Sep 22, 2010
    #1
    1. Advertisements

  2. s88

    Marc Guest

    That's not how operator() works, it is only for member functions, to be
    used as myobject(left,right).
    You can't redefine the meaning of parentheses, but you can redefine that
    of commas.

    struct A { int i; };
    int operator,(A a,A b){return a.i+b.i;}
    int main(){
    A a,b;
    a.i=2;
    b.i=3;
    std::cout << (a,b) << std::endl;
    }
     
    Marc, Sep 22, 2010
    #2
    1. Advertisements

  3. The function call operator is only definable as a member of a class, not
    as a stand-alone function. The compiler understands your syntax as

    cout << (operator,(a,b)) << endl;

    and, of course, 'a' has no effect and 'b' is the value of the expression
    in the parentheses.

    What you might want is to define the operator comma in your class, like so:

    class myClass {
    ...
    public:
    myClass operator,(myClass const& right) const {
    myClass const& left = *this;
    ... // do what you did earlier with 'left' and 'right'
    }
    };

    V
     
    Victor Bazarov, Sep 22, 2010
    #3
  4. s88

    Jim Langston Guest

    If I do
    std::cout << (1, 2, 3);
    the output is 3. The right most value is output. In this particular
    case, 1 and 2 do absolutely nothing since they have no side effects.

    However, if I do
    std::cout << ( foo(), bar(), 3 );
    then foo() and bar() would have effect, even though they are not
    output they may have side effects.

    Now, since ( x, y ) works this way, are you positive you want to
    change C++'s behavior for your own classes to act differently? What
    is wrong with just using a+b?
     
    Jim Langston, Sep 23, 2010
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.