0

I wrote a template function

    template <class T>
    size_t get_size(T const &vec)
    {
        if constexpr (std::is_pointer<T>::value)
        {
            std::cout << "pointer" << std::endl;
            return vec->size();
        }
        else
        {
            std::cout << "not pointer" << std::endl;
            return vec.size();
        }
    }

which determines the size of either the vec, or first references the underlying data and then calles size upon it. Now I wanted to add the case that vec is actually a shared_pointer. But how can I figure that out? Executing

std::shared_ptr<Vector> vec = std::make_shared<Vector>(Vector({1, 2, 3}));
    std::cout << typeid(vec).name() << std::endl;

gives me St10shared_ptrISt6vectorIiSaIiEEE as an output.

My idea was to somehow destructure the type to access the outermoste layer of the type. In that case I could add a if else case using the is_same function.

Thanks for your help!

newandlost
  • 935
  • 2
  • 10
  • 21
  • 3
    a simpler way would be overload them instead of using `if constexpr` – apple apple Jan 31 '23 at 15:45
  • Which C++ standard? – Marek R Jan 31 '23 at 15:49
  • 4
    You could use SFINAE or a concept to check if the type is dereferenceable. My suggestion though is to don't do this. Just require that `get_size` is passed a vector. Then your caller just has to do `get_size(*my_pointer_to_vector)` and you don't need to worry about it. Trying to take any pointer like type wont work with overloads as you'll always be adding overloads. – NathanOliver Jan 31 '23 at 15:53
  • questions like this depress me - how to use template magic to see if you are using something yoy probably should not be using in the first place? – Neil Butterworth Jan 31 '23 at 16:10

0 Answers0