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.

10
  • It's possible you're looking for template template parameters. Commented Mar 3, 2013 at 1:12
  • 3
    typename T2::value_type? Commented Mar 3, 2013 at 1:12
  • 1
    If you're sure that it's a pointer to an array class/type, you can do decltype((*myarray)[0]) Commented Mar 3, 2013 at 1:12
  • @SethCarnegie I forget, is that going to be a reference type? Might need to remove the reference. Commented Mar 3, 2013 at 1:13
  • @Pubby actually no, I just looked it up and it says that decltype(...) is the type, but decltype((...)) is the reference. Commented Mar 3, 2013 at 1:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.