0

I have a class in my code that is comparable to std::array<T1, N> and a function :

template <class T2>
inline void f(T2* const myarray)
{
    std::pair<double, /*SOMETHING*/> x;
}

Assuming that T2* is a pointer to my class comparable to std::array<T1, N>, I would like to know what I have to write instead of /*SOMETHING*/ to get T1 from the [] operator of myarray ?

Note : I don't ask for a more clever way to get the type from a pointer to std::array.

Vincent
  • 57,703
  • 61
  • 205
  • 388

1 Answers1

3

This works for me:

#include <type_traits>
#include <array>
#include <utility>

template <class T2>
inline void f(T2* const myarray)
{
    std::pair<double, typename T2::value_type> x;
    static_assert(std::is_same<decltype(x.second), int>::value, "");
}

int
main()
{
    std::array<int, 2> a;
    f(&a);
}

If your "array-like" class template doesn't have a value_type, the following should also work:

std::pair<double, typename std::remove_reference<decltype((*myarray)[0])>::type> x;

But just fyi, const-qualified parameters are not generally used, and in C++11 will even be a pessimization if you happen to return the parameter (as in):

return myarray;

Though in this case myarray is a pointer and it doesn't really matter that it is const in this case.

If you instead meant:

inline void f(T2 const* myarray)

(pointer to a const T2, instead of a const pointer to a T2)

then the above recipe needs a slight adjustment:

std::pair<double, typename std::remove_const<
                                   typename std::remove_reference<
                                      decltype((*myarray)[0])
                                   >::type
                                >::type> x;

If your "array-like" class template does have value_type, then the first suggestion:

std::pair<double, typename T2::value_type> x;

works no matter where the const is.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577