How to get dereferenced type of template member for function return type

Viewed 3802

How can I get the correct type T for the following function to_vector?

template<typename K> struct A { K* p; size_t n; std::string foo; };
template<typename K> struct B { K* p; size_t n; float bar[3]; };

template<typename X>
std::vector<T> to_vector(const X& x) {   // what is T?
    return std::vector<T>(x.p, x.p+x.n); 
}

I tried with decltype(*std::declval<X>().p) but this results in error: forming pointer to reference type ‘float&’ for the following example:

A<float> a = { new float[10], 10, "hello" };
std::vector<float> v = to_vector(a);

This is part of some bigger code and there are more types like A and B. But all have a pointer p and a length n.

5 Answers
Related