c++ - 只返回传递值的默认函数?

标签 c++ templates c++11 lambda std-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);
}

但我在一个非常特殊的情况下遇到了问题,如下所示:

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;}(仅返回传递值的函数)。

为了做到这一点,我必须写什么来代替 /*SOMETHING 1*//*SOMETHING 2*/

最佳答案

没有标准的仿函数可以做到这一点,但它很容易编写(尽管确切的形式存在争议):

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

关于c++ - 只返回传递值的默认函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15202474/

相关文章:

c++ - makeDelegate 函数不起作用

c++ - 为什么这个简单的 enable_if 不起作用?

c++ - 如何检测运行时正在使用哪个 CPU?

c++ - 从 std::string 到 std::vector<bool> 的快速转换

c++ - 组成 std​​::integral_constant 值

c++ - 尾随返回类型和标签分发

c++ - 强制编译器只接受编译时参数( float )

c++ - 线程导致意外崩溃

c++ - 如何使用带有常量指针作为参数的模板的派生指针

类模板的所有实例化的 C++ 簿记