Why can type conversion operator not be qualified with explicit?

G

Guest

Hello

I wonder why only constructors can be qualified with explicit to
prevent implicit conversion, but not conversion operators. To me the
following makes perfectly sense:

struct A {
explicit operator int() { return 0;} ;
};
void foo(int) {};
int main() {
A a;
foo( a ); // implicit conversion: should be prohibited by explicit
foo( static_cast<int>(a) ); // explicit conversion: ok
return 0;
}

Greetings

Flo
 
K

Karl Heinz Buchegger

Hello

I wonder why only constructors can be qualified with explicit to
prevent implicit conversion, but not conversion operators. To me the
following makes perfectly sense:

struct A {
explicit operator int() { return 0;} ;
};
void foo(int) {};
int main() {
A a;
foo( a ); // implicit conversion: should be prohibited by explicit
foo( static_cast<int>(a) ); // explicit conversion: ok
return 0;
}

Greetings

I can only guess:
Because you could write an ordinary function to do what you want to do?

struct A {
int AsInt() { return 0; }
};

void foo(int) {};
int main()
{ A a;
foo( a ); // implicit conversion: should be prohibited by explicit
foo( a.AsInt() ); // explicit conversion: ok
return 0;
}
 
V

Victor Bazarov

I wonder why only constructors can be qualified with explicit to
prevent implicit conversion, but not conversion operators. To me the
following makes perfectly sense:

struct A {
explicit operator int() { return 0;} ;
};
void foo(int) {};
int main() {
A a;
foo( a ); // implicit conversion: should be prohibited by explicit
foo( static_cast<int>(a) ); // explicit conversion: ok
return 0;
}

IIRC, there is a defect report on that... Lemme see... Nope, can't find
any... But I remember conversations about it. Probably in the newsgroup
archives... Let's go there... Yep. Plenty of discussions. Try this:

http://groups.google.com/groups?q=type+conversion+operator+explicit&hl=en

V
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

I wonder why only constructors can be qualified with explicit to
prevent implicit conversion, but not conversion operators. To me the
following makes perfectly sense:

struct A {
explicit operator int() { return 0;} ;
};
void foo(int) {};
int main() {
A a;
foo( a ); // implicit conversion: should be prohibited by explicit
foo( static_cast<int>(a) ); // explicit conversion: ok
return 0;
}

Probaby because is easy and more legible to write a: 'int to_int ();' member
function.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top