Change only parts of a type in a C ++ template

Goal and craziness aside, is there a way to achieve this in C ++?

template <typename P>
void Q void_cast(P Q *p) const
{
    return static_cast<P Q *>(p);
}

I am effectively trying to direct a pointer to a pointer type void, while preserving any const, restrictand other qualifiers (indicated Q).

I got the impression that there are materials in the C ++ standard library (or less desirable in Boost) that allow you to "customize" type properties with less granularity than saying const_castor static_cast.

+3
source share
3 answers

So you want const X*β†’ const void*, volatile X*β†’ volatile void*, etc.

:

template<typename P>
void* void_cast(P* p)
{
    return p;
}

template<typename P>
void const* void_cast(P const* p)
{
    return p;
}

template<typename P>
void volatile* void_cast(P volatile* p)
{
    return p;
}

template<typename P>
void const volatile* void_cast(P const volatile* p)
{
    return p;
}

- , add_const, add_volatile, remove_const remove_volatile. cv- , cv- .

+7
template<class From>
typename copy_rpcv<void, From*>::type void_cast(From *p) {
  return p;  // implicit conversion works
}

TMP:

// "copy ref/pointer/const/volatile"
template<class To, class From>
struct copy_rpcv {
  typedef To type;
};
template<class To, class From> struct copy_rpcv<To, From&        > { typedef typename copy_rpcv<To, From>::type&         type; };
template<class To, class From> struct copy_rpcv<To, From*        > { typedef typename copy_rpcv<To, From>::type*         type; };
template<class To, class From> struct copy_rpcv<To, From const   > { typedef typename copy_rpcv<To, From>::type const    type; };
template<class To, class From> struct copy_rpcv<To, From volatile> { typedef typename copy_rpcv<To, From>::type volatile type; };

; , , , , , 03 ( 0x?), :

template<class To, class From> struct copy_rpcv<To, From* restrict> { typedef typename copy_rpcv<To, From>::type* restrict type; };

Anthony's "" :

int *const *const p = 0;
void *const *const v = void_cast(p);
+1
source

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


All Articles