I donโt know of any built-in template, but itโs not too difficult to create your own (that once nested, there will be no overhead):
template<typename T, typename K> struct subscript { inline auto operator()(T const& obj, K const& key) const -> decltype(obj[key]) { return obj[key]; } inline auto operator()(T& obj, K const& key) const -> decltype(obj[key]) { return obj[key]; } };
You might even have one that worked on implicit types (I like it best):
struct subscript { template<typename T, typename K> inline auto operator()(T&& obj, K&& key) const -> decltype(std::forward<T>(obj)[std::forward<K>(key)]) { return std::forward<T>(obj)[std::forward<K>(key)]; } };
The user, of course, can pass in any appropriate type, including std::function objects or simple function pointers.
source share