As a lazy developer, I like to use this trick to specify a default function:
template <class Type, unsigned int Size, class Function = std::less<Type> >
void arrange(std::array<Type, Size> &x, Function&& f = Function())
{
std::sort(std::begin(x), std::end(x), f);
}
But I have a problem in a very particular case, which is the following:
template <class Type, unsigned int Size, class Function = /*SOMETHING 1*/>
void index(std::array<Type, Size> &x, Function&& f = /*SOMETHING 2*/)
{
for (unsigned int i = 0; i < Size; ++i) {
x[i] = f(i);
}
}
In this case, I would like the default function to be the equivalent of: [](const unsigned int i){return i;}
(a function that just returns the passed value).
In order to do that, what do I have to write instead of /*SOMETHING 1*/
and /*SOMETHING 2*/
?
Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
A function default value is a value that can be used for a parameter if the calling statement does not pass an argument. If an argument is provided, the default value is ignored.
Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call.
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.
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