Default function that just returns the passed value?

前端 未结 6 1516
礼貌的吻别
礼貌的吻别 2020-12-31 08:24

As a lazy developer, I like to use this trick to specify a default function:

template 

        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 09:13

    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
        constexpr auto operator()(U&& v) const noexcept
            -> decltype(std::forward(v))
        {
            return std::forward(v);
        }
    };
    

    This can be used as follows:

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

提交回复
热议问题