Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default function that just returns the passed value?

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*/?

like image 779
Vincent Avatar asked Mar 04 '13 13:03

Vincent


People also ask

How do you pass a default value in a function?

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.

What is default value function?

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.

What is a default function?

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.

What is default argument function in Python?

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.


1 Answers

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.

like image 109
Olaf Dietsche Avatar answered Oct 21 '22 14:10

Olaf Dietsche