Does the C++11/14/17 standard library have a way to cast an object to a different type but with the same cv-qualifiers as the original object? E. g.
char* ptr;
const char* cptr;
type_cast<void*>(ptr) should yield the type void*
type_cast<void*>(cptr) should yield the type const void*
Not in the standard library, but it is certainly possible to implement it yourself:
namespace detail_base_type_cast {
template <class In, class Out>
struct copy_cv {
using type = Out;
};
template <class In, class Out>
struct copy_cv<In const, Out &> {
using type = Out const &;
};
template <class In, class Out>
struct copy_cv<In volatile, Out &> {
using type = Out volatile &;
};
template <class In, class Out>
struct copy_cv<In const volatile, Out &> {
using type = Out const volatile &;
};
}
template <class Out, class In>
typename detail_base_type_cast::copy_cv<In, Out>::type
base_type_cast(In &obj) {
return obj; // Implicit derived-to-base conversion
}
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