user3442005
user3442005

Reputation: 103

Function Overloading using Enum

I was going through examples of function overloading and came across the following example:

#include <string>
#include<iostream>

using namespace std;

enum e1 {a1, b1, c1};
enum e2 {a2, b2, c2 = 0x80000000000 };

string format (int){
    cout<<1;
}
string format (unsigned int){
    cout<<2;
}


int main () { 
    format (a1);
    format (a2);
    return 0; 
}

Using gcc 5.4.0, format(a1) compiles and format(int) is called (displays 1 as output). But, when format(a2) is compiled, the following error appears:

 call of overloaded 'format(e2)' is ambiguous

Shouldn't format(a2) and format(a1) have the same output/error?

Upvotes: 1

Views: 1336

Answers (1)

Justin
Justin

Reputation: 25347

enum e2 {a2, b2, c2 = 0x80000000000 };

The literal 0x80000000000 is of type long. A regular enum (not an enum class) has an underlying type large enough to hold all its values 7.2 [dcl.enum], thus e2 must be at least a long.

On the other hand, e1's values all fit inside an int/unsigned int, so its underlying type must be one of those.

When I tested it on godbolt, the underlying type of e1 was unsigned int, and the underlying type of e2 was unsigned long. Thus, when calling the functions, format(a1) unambiguously calls the unsigned int version, but format(a2) now has to convert from an unsigned long, so it's unclear which function to call.

Upvotes: 1

Related Questions