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?
The subscript operator is commutative. Therefore, the expressions array[index] and index[array] are guaranteed to be equivalent as long as the subscript operator is not overloaded (see Overloaded Operators). The first form is the most common coding practice, but either works.
Overloading Subscript or array index operator [] in C++The Subscript or Array Index Operator is denoted by '[]'. This operator is generally used with arrays to retrieve and manipulate the array elements. This is a binary or n-ary operator and is represented in two parts: postfix/primary expression.
There isn't a double-subscript operator in C++. What you can do is overload operator[] to return an object that also overloads operator[] . This will enable you to write m[i][j] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With