joaocandre
joaocandre

Reputation: 1745

How to extract type from empty templated container using decltype?

What would the correct decltype syntax to extract the data type from a specific container class, without recurring to a value_type member typedef?

I was attempting to directly access an element with decltype<std::declval<myContainerClass>[0]> but I realize it wouldn't work if the container is empty.

Upvotes: 0

Views: 212

Answers (1)

Brian Bi
Brian Bi

Reputation: 119457

You can use

std::remove_reference_t<decltype(std::declval<Container>()[0])>

Everything inside decltype is unevaluated, so the fact that accessing element 0 of a hypothetical empty container is UB doesn't matter. This just extracts the necessary type information from the container's operator[]. You need the remove_reference because operator[] probably returns an lvalue reference.

However, this wouldn't work for a container such as std::list<T>. Instead, you can use:

typename std::iterator_traits<typename Container::iterator>::value_type

If you can't assume Container::iterator exists, you can replace typename Container::iterator with decltype(std::declval<Container>().begin()).

Upvotes: 4

Related Questions