You could invoke this as:
auto foo = mymap.operator[]<int>("key");
...but if you're going to do that, you'd be a lot better off making it a normal member function:
template<typename T>
const T & get(const std::string & name) const {
auto aux = map[name];
return std::any_cast<T&>(aux);
}
...so calling it would be something like auto foo = mymap.get<int>("key");
The other obvious possibility would to pass a reference to the destination, so the type can be inferred. You can't do that with operator[]
(which only accepts one argument), but you can with operator()
(which accepts an arbitrary number of arguments):
template <typename T>
void operator()(std::string const &name, T &dest) {
dest = std::any_cast<T>(map[name]);
}
int foo;
mymap("key", foo);
I think I prefer the get
version though.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…