Error Ambiguous on signed / unsigned

Discussion in 'C++' started by Nephi Immortal, Oct 8, 2011.

  1. I have two types – signed long and unsigned long. Are they really
    signed int type? If unsigned long type is chosen, signed int is
    chosen by C++ Compiler unless I declare explicit cast or error
    ambiguous is reported.

    void Do( signed int x ) {}
    void Do( unsigned int x ) {}

    int main()
    {
    signed long a = -1;
    unsigned long b = 1u;

    Do( a ); // OK
    Do( b ); // error ambiguous
    Do( static_cast< unsigned int >( b )); // OK
    };

    How can I use implicit cast and let C++ Compiler match signed int or
    unsigned int?
     
    Nephi Immortal, Oct 8, 2011
    #1
    1. Advertising

  2. Nephi Immortal

    Geoff Guest

    On Sat, 8 Oct 2011 09:51:35 -0700 (PDT), Nephi Immortal
    <> wrote:

    > I have two types – signed long and unsigned long. Are they really
    >signed int type? If unsigned long type is chosen, signed int is
    >chosen by C++ Compiler unless I declare explicit cast or error
    >ambiguous is reported.
    >
    >void Do( signed int x ) {}
    >void Do( unsigned int x ) {}
    >
    >int main()
    >{
    > signed long a = -1;
    > unsigned long b = 1u;
    >
    > Do( a ); // OK
    > Do( b ); // error ambiguous
    > Do( static_cast< unsigned int >( b )); // OK
    >};
    >
    > How can I use implicit cast and let C++ Compiler match signed int or
    >unsigned int?


    You can't.

    The ambiguity is not signed vs. unsigned but int vs long. The language
    is protecting you from committing an error by stuffing a long argument
    into an int without explicitly telling the compiler that you want it.

    void Do( signed int x ) {}
    void Do( unsigned int x ) {}
    void Do( signed long x ) {}
    void Do( unsigned long x ) {}

    int main()
    {
    signed long a = -1;
    unsigned long b = 1u;

    Do( a ); // OK
    Do( b ); // OK
    Do( static_cast< unsigned int >( b )); // OK
    }
     
    Geoff, Oct 8, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    841
    Martin Thompson
    Jan 10, 2007
  2. kyrpa83
    Replies:
    1
    Views:
    626
    kyrpa83
    Oct 17, 2007
  3. mathieu
    Replies:
    3
    Views:
    676
    James Kanze
    Nov 18, 2008
  4. Rob1bureau
    Replies:
    1
    Views:
    814
    joris
    Feb 27, 2010
  5. pozz
    Replies:
    12
    Views:
    745
    Tim Rentsch
    Mar 20, 2011
Loading...

Share This Page