Is it possible to define a custom converter (converter1<T>
and converter2
) between different types of raw pointer A*
and B*
,
then make all functions (fa()
and fb()
) in a certain class
use an appropriate converter (converter1<T>
or converter2
)?
In short, I want the program to convert A*
to B*
and vice versa USING my custom functions.
I wish it would do that automatically for my convenience.
class Manager{
void fb(B* b){ /** something complex */ }
void fa(A* a){ /** different thing complex */ }
void testCase(){
A* a= ... ;
fa(a);
fb(a); //automatic convert to B* using "converter2" (wish)
B* b= ... ;
fa(b); //automatic convert to A* using "converter1" (wish)
fb(b);
}
template<class T> T* converter1(B* b){ //hardcoded, non-static.
return this->getId<T>(b);
//^^^ just an example to show how custom it is,
// currently T=A
}
B* converter2(A* a){ //hardcoded
return a->getB();
//^^^ just an example to show how custom it is.
}
}
The real case has many A
- A1
, A2
, A3
and so on.A
and B
are not derived from each other.
I wish there is a way. I think about constructor of pointer.
A raw pointer is a pointer whose lifetime is not controlled by an encapsulating object, such as a smart pointer. A raw pointer can be assigned the address of another non-pointer variable, or it can be assigned a value of nullptr. A pointer that hasn't been assigned a value contains random data.
Boost your efficiency with refactorings, code analysis, unit test support, and an integrated debugger. You cannot convert (i.e. perform type cast) raw pointer to unique_ptr, but you can initialize unique_ptr with raw pointer. ....
Outside of memory management code, the only real justification for that would be passing something by pointer to external code that says it will assume ownership of the passed-in raw pointer. Even then, you really should use a unique ptr and just call release on it when passing to the foreign code. I use raw pointers all the time.
(If no custom converter is available, a JsonException exception is thrown by the internal converter for the type.) This null-handling behavior is primarily to optimize performance by skipping an extra call to the converter.
No this is not possible.
Pointers are built-in types and only built-in conversions between built-in types exist. User-defined conversions only work for user-defined class types.
You may want to switch to your own brand of smart pointers to handle this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With