Default function that just returns the passed value?

This is called the identity function. Unfortunately, it is not part of the C++ standard, but you can easily build one yourself.


If you happen to use g++, you can activate its extensions with -std=gnu++11 and then

#include <array>
#include <ext/functional>

template <class Type, std::size_t Size, class Function = __gnu_cxx::identity<Type> >
void index(std::array<Type, Size> &x, Function&& f = Function())
{
    for (unsigned int i = 0; i < Size; ++i) {
        x[i] = f(i);
    }
}

Maybe it will be available in C++20, see std::identity. Until then you may look at boost's version at boost::compute::identity.


There is no standard functor that does this, but it is easy enough to write (though the exact form is up for some dispute):

struct identity {
    template<typename U>
    constexpr auto operator()(U&& v) const noexcept
        -> decltype(std::forward<U>(v))
    {
        return std::forward<U>(v);
    }
};

This can be used as follows:

template <class Type, std::size_t Size, class Function = identity>
void index(std::array<Type, Size> &x, Function&& f = Function())
{
    for (unsigned int i = 0; i < Size; ++i) {
        x[i] = f(i);
    }
}