Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Why enum is automatically converted in class member but not in global function

31 views
Skip to first unread message

JiiPee

unread,
Dec 4, 2019, 7:53:36 PM12/4/19
to
I wonder why the compiler does automatic type conversion for an enum to
int if the function is a class member, but does not do that if the
function is a global function.

Example code:

enum MyEnum
{
enumVal1
}


1)
+= as a class member:

template <typename T>
inline void MyClass<T>::operator += (const T& val)
{
}

MyClass<int> obj;
obj += enumVal1; // converts enumVal1 to int and calls operator +=

This all works.

2)

The same += as a global function:

template <typename T>
inline void operator += (const MyClass<T>& obj, const T& val)
{
}

obj += enumVal1; // does not convert enumVal1 to int

This one does not compile, I get this error:
"+= does not define this operator or a conversion to a type acceptable
to the predefined operator"


Bo Persson

unread,
Dec 4, 2019, 8:57:11 PM12/4/19
to
It has to do with the order of type deduction and overload resolution.
Type deduction is always performed first.

In the first case, T is given from the use of MyClass<int>. That class
instantiation has a member operator that takes an int, and the enum is
convertible to int. Good.


In the second case, the compiler is looking for an operator that takes a
class object and an enum value. There isn't any.

The fact that the enum might be convertible to some other type that
would match the template doesn't help, as type deduction is performed
first and enumVal1 just isn't a T. So that template is not added to the
potential overload set.



Bo Persson

JiiPee

unread,
Dec 5, 2019, 9:21:11 AM12/5/19
to
ok, thanks. A little difficult to google these issues, thats why asked
here :)


0 new messages