Why we can not overload the static_cast operator?

G

Guest

In C++ we can not overload the explicit typecast operator like
static_cast, dynamic_cast, const_cast and reinterpret_cast. The only
we can do is the implicit typecast operator like operator
MyClass::MyDistType().

I agree there are maybe no meaning to overload dynamic_cast/const_cast/
reinterpret_cast, except the static_cast. If we enable the overloading
of static_cast, we could be able to force the user doing type casting
explicitly.

There are two ways to implemation this:

Suggestion 1:

class B;
class A
{
public:
friend B operator static_cast<B>(const A &);
};

A a;
// B b=a; //Error, no type casting operator
B b=static_cast<B>(a); //Pass, using the friend casting operator

Suggestion 2:

class B;
class A
{
public:
explicit operator B();
};

A a;
// B b=a; //Error, the type casting operator decalred as explicit
B b=static_cast<B>(a) //Pass, using explicit type casting
 
V

Victor Bazarov

????? said:
In C++ we can not overload the explicit typecast operator like
static_cast, dynamic_cast, const_cast and reinterpret_cast. The only
we can do is the implicit typecast operator like operator
MyClass::MyDistType().

I agree there are maybe no meaning to overload
dynamic_cast/const_cast/ reinterpret_cast, except the static_cast. If
we enable the overloading of static_cast, we could be able to force
the user doing type casting explicitly.

There are two ways to implemation this:

Suggestion 1:

class B;
class A
{
public:
friend B operator static_cast<B>(const A &);
};

A a;
// B b=a; //Error, no type casting operator
B b=static_cast<B>(a); //Pass, using the friend casting operator

Suggestion 2:

class B;
class A
{
public:
explicit operator B();
};

A a;
// B b=a; //Error, the type casting operator decalred as explicit
B b=static_cast<B>(a) //Pass, using explicit type casting

I think that has been discussed a couple of times in the past.
In fact, I vaguely remember that there was a valid reason not to
allow 'explicit' with the type conversion function. But I don't
recall what it was.

Try looking on 'groups.google.com'. You should find something.

V
 

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,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top