Automatic type conversion for templates with const / non-const pointer types

Is it possible to provide automatic conversion for a template class created using pointer types const and non-const?

In particular, consider the following:

template <typename T> class A { public: operator A<const T>() { return A<const T>(); } }; int main() { A<const int> a1; A<int> a2; // Works fine; invokes operator A<const T>() a1 = a2; A<const int*> a3; A<int*> a4; // Fails to compile: no viable overloaded '=' a3 = a4; return 0; } 

Is it possible to provide an explicit type conversion with pointer pattern arguments? What would it look like in the definition of A?

As a bonus / background question, why does this work for template arguments without a pointer, but not for pointer template arguments?

+5
source share
1 answer

The source of the confusion is the pointer constant versus the bridgehead constant. You now have the setting T set to const T If you replace int with T , it will work, int will become const int . However, if you replace int * , you will get int * const , not const int * . T gets const , which is a pointer, so the pointer becomes const , not the object it points to.
The following code works:

 A<int*const> a5; A<int*> a6; // compiles a5 = a6; 

You can do some difficult things, such as

 operator A<std::add_pointer_t<std::add_const_t<std::remove_pointer_t<T>>>>() { return {}; } 

do a3 = a4; compilation, but you have to be very careful that these conversions actually do what they were supposed to do (the above example incorrectly (?) allows you to convert int to const int * , because remove_pointer does nothing if this type is not a pointer, it will require enable_if + is_pointer , which becomes quite complicated).

+4
source

All Articles