Operator overload crisis

This is a discussion on Operator overload crisis within the C++ Programming forums, part of the General Programming Boards category; I want two forms of every overload I do: for the + operator: template <typename UnknownType> any operator +(const any ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    417

    Operator overload crisis

    I want two forms of every overload I do:

    for the + operator:

    template <typename UnknownType>
    any operator +(const any & lhs, const UnknownType & rhs)

    and

    template <typename UnknownType>
    UnknownType operator +(const UnknownType & lhs, const any & rhs)

    The problem is that apparently it is converting ALL types to an any, irrelevant what the data is...

    I want to make it so that if it isn't an any already, it will NOT try to use the constructor to make it one.

    How?

    otherwise I get this:
    error C2666: '!=' : 3 overloads have similar conversions

    If I'm NOT using an any.

    I believe that is the problem (that it is running the constructor) because if I comment out the one with the any parameter first, it runs.

    How can I fix this?
    Last edited by Trauts; 05-14-2003 at 05:59 PM.

  2. #2
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,136
    Try making the constructor explicit if it isn't.

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    If I make it explicit, then the times that that would be what I want wouldn't work.

    Is there a way to add different functions to a STL class?

    I.e. rewrite the push_back function with an overload?

    its the difference between doing this with a std::vector/list:

    Code:
    std::vector<any> x;
    x.push_back(10);
    x.push_back('a');
    and

    Code:
    std::vector<any> x;
    x.push_back(any(10));
    x.push_back(any('a'));
    also, the most important part:

    Code:
    any x;
    x = 5;
    That no longer would work because that calls the constructor.

    Otherwise, your method is perfect! So can I change a STL class?

    Or best of all, can you make it explicit only in certain functions?
    Last edited by Trauts; 05-14-2003 at 07:42 PM.

  4. #4
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    bool operator !=(explicit any & lhs, const UnknownType & rhs)

    why can't I do that?

    also... if I remove the const from the function (any & lhs)... it works. Thats not good though, because now it could be modified.

    Why does it work though?
    Last edited by Trauts; 05-14-2003 at 07:52 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What about the oil crisis?
    By VirtualAce in forum A Brief History of Cprogramming.com
    Replies: 22
    Last Post: 10-23-2008, 09:12 AM
  2. Crisis du jour: (Linux) Array Error
    By JKI in forum C++ Programming
    Replies: 5
    Last Post: 10-02-2003, 09:44 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21