Add const to pointer type

Viewed 288

Say I have a class template:

template <class T>
struct A
{
  T value;

  void foo(auto fun) { 
    fun(value);
    // ^^^^^^^ Pass value as a const object
  }
};

I want to add const to the value, when calling fun so that only functions that accept T, T const&, T const* are callable. My initial approach was to make foo a const member function, but this fails for reference and pointer members, since const member functions can modify them (you just cannot rebase those members).

I also try to use std::add_const and std::as_const to pass the value to the argument function (fun) but this makes a transformation like the following:

T = MyData*                  // say T is the type "Pointer to MyData"
add_const<T> = MyData *const // constness is added to the pointer, 
                             // i.e. it becomes constant pointer to MyData

The target type I'd like to have in the example above is MyData const* (pointer to constant MyData).

  • Is there a standard facility to achieve this?
  • Is there a different way to do it, I mean other than decorating the call fun(value)?

Demo

1 Answers

You can

fun(static_cast<std::conditional_t<
                    std::is_pointer_v<T>,
                    std::add_pointer_t<std::add_const_t<std::remove_pointer_t<T>>>,
                    std::add_const_t<T>
                >
               >(value));

Then when T is MyData*, the converted type would be MyData const*; for non-pointer type like MyData the converted type would be MyData const.

Related