I'd like to implement the * and -> operators for the iterator of a custom-made container. My code doesn't compile. Below a "Minimal Non-working example", which shows how it works with std::map but not in my code.
#include <vector>
#include <map>
#include <iostream>
struct thing {
float f[1];
typedef std::pair<int,float> key_data;
struct iterator {
int pos;
const float *f;
key_data operator*() const { return key_data(pos,f[pos]); }
key_data *operator->() const { return &key_data(pos,f[pos]); }
};
iterator begin() const { return {.f = f, .pos = 0}; }
};
template<typename T> void test(T iter) {
(*iter).second = 1.0; std::cout << (*iter).second;
iter->second = 2.0; std::cout << iter->second;
}
int main() {
std::map<int,float> fmap; fmap[0] = 0.0;
test(fmap.begin());
std::cout << fmap[0];
thing f;
test(f.begin());
std::cout << f.f[0];
}
I would like this to compile :), and print 122122. The error messages on compilation are:
access.cc:13:43: error: taking the address of a temporary object of type 'key_data'
(aka 'pair<int, float>') [-Waddress-of-temporary]
key_data *operator->() const { return &key_data(pos,f[pos]); }
access.cc:20:18: error: expression is not assignable
(*iter).second = 1.0; std::cout << (*iter).second;
For the first: fair enough, std::pair<> creates a temporary which can't be returned by reference; but how does STL do it to allow the usual -> syntax?
For the second: probably again I'm trying to assign into a temporary, but I can't guess what the right syntax is.
Many thanks in advance!
Aucun commentaire:
Enregistrer un commentaire