c++templatesconstantstype-traitsconst-correctness

How do you add const to the pointed-to type?


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).

Demo


Solution

  • You can

    using target_type = std::conditional_t<std::is_pointer_v<T>,
                                           std::remove_pointer_t<T> const*,
                                           T const>;
    fun(static_cast<target_type>(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.