Implementing variadic min / max functions

后端 未结 6 1937
灰色年华
灰色年华 2020-12-14 06:06

I\'m implementing variadic min/max functions. A goal is to take advantage of the compile time known number of arguments and perform an unrolled evaluation (

6条回答
  •  轮回少年
    2020-12-14 07:07

    4) Here is one possible way to implement a constexpr version of this function:

    #include 
    #include 
    
    template 
    constexpr typename std::common_type::type vmin(Arg1&& arg1, Arg2&& arg2)
    {
        return arg1 < arg2 ? std::forward(arg1) : std::forward(arg2);
    }
    
    template 
    constexpr typename std::common_type::type vmin(Arg&& arg, Args&&... args)
    {
        return vmin(std::forward(arg), vmin(std::forward(args)...));
    }
    
    int main()
    {
        std::cout << vmin(3, 2, 1, 2, 5) << std::endl;
        std::cout << vmin(3., 1.2, 1.3, 2., 5.2) << std::endl;
    }
    

    See live example.

    Edit: As @Yakk noted in comments the code std::forward(arg1) < std::forward(arg2) ? std::forward(arg1) : std::forward(arg2) may cause problems in some situations. arg1 < arg2 ? std::forward(arg1) : std::forward(arg2) is more appropriate variant in this case.

提交回复
热议问题