Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in way to cast to a different underlying type but preserve const qualifiers?

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*

like image 393
Violet Giraffe Avatar asked Dec 02 '25 23:12

Violet Giraffe


1 Answers

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
}
like image 120
Quentin Avatar answered Dec 05 '25 13:12

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!