Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload the *static_cast* operator?

Tags:

c++

casting

I have defined a class A, the actual properties are irrelevant. Is it possible to define a specialization of the static_cast<class T>(int) operator to convert from integers to class A?

So far I have been doing this by defining a convert function, such as A convert(int). But I would rather use static_cast for consistency with other conversions.

Is it possible?
I also want to avoid implicit conversions, which is why I'm not doing this through A's constructor.

like image 465
Malabarba Avatar asked Dec 08 '11 14:12

Malabarba


1 Answers

static_cast is a keyword, so there's nothing you can overload or override there. If you want to provide code that controls how integers are transformed into class A instances, write an appropriate constructor of the form A::A(int).

Update: If you want to avoid implicit conversions, you can make this constructor explicit. Somehow I didn't quite read the last sentence of the question, apologies.

like image 65
Jon Avatar answered Sep 28 '22 07:09

Jon