Is it possible to overload the * static_cast * operator?

I defined class A, the actual properties do not matter. Is it possible to define the specialization of the static_cast<class T>(int) operator for converting from integers to class A?

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

Is it possible?
I also want to avoid implicit conversions, so I do not do this through the constructor.

+6
source share
7 answers

static_cast is a language keyword, and you cannot do anything to change this. However, you can achieve that with an explicit conversion constructor:

 class Foo { explicit Foo(int bar) { } // Can't be called implicitly, CAN be invoked with `static_cast`. }; 

This works because the language defines the behavior of static_cast in terms of building the object, causing conversions if necessary.

+7
source

static_cast is a keyword, so you cannot overload or override anything there. If you want to provide code that controls the conversion of integers to instances of class A , write the appropriate constructor of the form A::A(int) .

Update: If you want to avoid implicit conversions, you can make this constructor explicit . Somehow I did not quite read the last sentence of the question, apologized.

+9
source

If you want to avoid implicit conversions. Why don't you use an explicit keyword?

+7
source

If A has an A(int) conversion constructor, it will be called C ++ when you use static_cast<A> for objects of type int .

+2
source

Yes and no. You cannot define operator static_cast() , but static_cast will always call either a constructor or operator conversion: support int to MyClass , provide MyClass with a constructor that can be called with int ; to support MyClass int , specify MyClass using the operator int() const function.

+2
source

Is it possible to determine the specialization of the static_cast (int) operator for converting from integers to class A

Not. static_cast is a keyword, not a template or function.

However, in your class A you can write a constructor that accepts int if you want this behavior.

 struct A { A(int i) {} }; A a = 10; //automatic conversion! 

Or, if you need some sort of syntactic sugar that should look like the cast, you can do this:

 template<typename To, typename From> To type_cast(From from) { return To(from); } 

then use it like:

 A a = type_cast<A>(10); //but why would you do that? 

But why do you have to do this? I see no advantage in this; therefore, I am preventing you from writing such a function template. I showed you this only for experimental and educational purposes. Such code should not be in real code.

+1
source

Why not use a constructor with int ?

 struct MyInteger { MyInteger(int i); }; int main() { MyInteger i = 1234; } 
0
source

Source: https://habr.com/ru/post/903384/


All Articles