默认功能,只是返回传递的值?(Default function that just returns

2019-07-20 22:36发布

作为一个懒惰的开发者,我喜欢用这种伎俩来指定一个默认功能:

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

Answer 1:

还有就是做这个没有标准的函子,但它是很容易的写(但具体形式则弥补了一些争议):

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


Answer 2:

提高::凤凰提供了一个完整的功能工具箱,在这里“ARG1”是的ident身份;-)

#include <boost/phoenix/core.hpp>

template <class X, class Function = decltype(boost::phoenix::arg_names::arg1)>
void index(X &x, Function f = Function()) {
    for (std::size_t i = 0; i < x.size(); ++i) {
            x[i] = f(i);
  }
}


Answer 3:

这就是所谓的identity功能。 不幸的是,它不是C ++标准的一部分,但你可以轻松地构建一个自己。


如果你碰巧使用G ++,你可以激活它的扩展与-std=gnu++11 ,然后

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

也许它会在C ++ 20可用,看到std::identity 。 在那之前,你可以看升压转换器的版本在升压::计算::身份 。



Answer 4:

你可以建立自己的身份的仿函数:

template <typename T>
class returnIdentifyFunctor
{
  public:
     auto operator ()(  T &&i ) -> decltype( std::forward<T>(i) )
    {
      return std::move(i);
    }
};

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


Answer 5:

对付这种情况的方法是有两个不同的功能。 我觉得挺理智使用默认参数。

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

template<class Type, unsigned int Size>
void index(std::array<Type, Size> &x){
    return index(x, [](unsigned int i){return i;});                      // C++11 in this case
                //, [](auto&& e){return std::forward<decltype(e)>(e)};); // C++14 in a more general case
                //, std::identity); // C++20 in general
}


文章来源: Default function that just returns the passed value?