默认函数只返回传递的值? [英] Default function that just returns the passed value?

查看:90
本文介绍了默认函数只返回传递的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个懒惰的开发人员,我喜欢使用这个技巧来指定一个默认的函数:

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);
    }
}

在这种情况下,我想使用默认函数相当于: [](const unsigned int i){return 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).

为了做到这一点,我需要写什么而不是 / * SOMETHING 1 * / / * SOMETHING 2 * /

In order to do that, what do I have to write instead of /*SOMETHING 1*/ and /*SOMETHING 2*/?

推荐答案

没有标准函子可以做到这一点, (虽然确切的形式是有争议的):

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);
    }
};

这可以使用如下:

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);
    }
}

这篇关于默认函数只返回传递的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆