Standard C ++ function object template for index operator

Let's 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 configure the substring operation so that the user can apply their own code to match obj and key with the return value. Something like that:

 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 ( std::less<T> ) that I can use here so that Op calls operator[] by default? I do not see anything suitable in <functional> .

If there is no standard template for this, would I rather create my own or is there a way that I can use std::bind() or similarly to the same effect without additional overhead?

+6
source share
1 answer

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.

+2
source

Source: https://habr.com/ru/post/951994/


All Articles