chenzhongpu
chenzhongpu

Reputation: 6871

C++: how to use decltype to get type from iterator

Firstly, I have a forward_list:

forward_list<int> f {1, 0, 5, 4};
auto i = *(f.begin());
auto beg = f.begin();

Then I try to build a vector from f, and I would like to use decltype to get the type from iterator.

vector<decltype(*beg)> v{f.begin(), f.end()}; // compile error

But

vector<decltype(i)> v{f.begin(), f.end()};

works well.

The error information are mainly related to memory:

error: 'pointer' declared as a pointer to a reference of type 'int &'

error: 'const_pointer' declared as a pointer to a reference of type 'int &'

Upvotes: 2

Views: 597

Answers (1)

Jans
Jans

Reputation: 11250

Use std::iterator_traits instead:

using type = std::iterator_traits<decltype(beg)>::value_type;
std::vector<type> v{f.begin(), f.end()};

or decay the dereferenced iterator type

using type = std::decay_t<decltype(*beg)>;
std::vector<type> v{f.begin(), f.end()};

Upvotes: 1

Related Questions