Standard C++ function object template for the subscript operator
c++, c++11
Solution
I don't know of any built-in template, but it's not too hard to create your own (that, once inlined, will have 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 could even have one that worked on implicit types (I like this one 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 conforming type of their own, including a `std::function` object or plain function pointers.
Problem
Say I currently have a template function like this: ``` template <class T, class K> void* get_subobject(K key) { T& obj = function_returning_T_ref<T>(); // do various other things... return &obj[key]; } ``` And I would like to make the subscript operation configurable so that the user could apply their own code to map `obj` and `key` to the return value. Something like this: ``` template <class T, class K, class Op = subscript<T, K>> void* get_subobject(K key) { T& obj = function_returning_T_ref<T>(); // do various other things... return &Op{}(obj, key); } ``` My question is, for the default template parameter `subscript<T,K>` above is there a standard template (along the lines of `std::less<T>`) that I can use here so that `Op` defaults to calling `operator[]`? I can't see anything appropriate in `<functional>`. If there is no standard template for this, am I best to create my own or is there some way I can use `std::bind()` or similar to the same effect without additional overhead?