Reputation: 1771
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
template <typename T>
auto Copy(T c)
{
std::vector<decltype(c.begin()->first)> lc;
//Copying
return lc;
}
int main()
{
std::map<int, int> map;
Copy(map);
return 0;
}
In the above code I am trying declare a vector
from the datatype of keys of map
but I am getting following error -
"The C++ Standard forbids containers of const elements allocator<const T> is ill-formed."
Upvotes: 2
Views: 3091
Reputation: 93284
The problem is that decltype(c.begin()->first)
returns a const int
(when using libstdc++ - your example compiles with libc++).
As your error tells you...
The C++ Standard forbids containers of const elements because allocator< const T > is ill-formed.
A possible solution is using std::decay_t
:
std::vector<std::decay_t<decltype(c.begin()->first)>> lc;
This will guarantee that your example works both with libstdc++ and libc++. Alternatively, std::remove_const_t
also works in this particular situation.
Here's a working example on wandbox.
Upvotes: 7