Why is this “min” template of cpp-next at fault?

前端 未结 5 700
时光取名叫无心
时光取名叫无心 2021-01-03 21:39

I was reading cpp-next where this min template is presented as an example of how verbose C++ code can be compared to python code

template 

        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 21:48

    rev 3: KonradRudolph

    template 
    auto min(T x, U y) -> typename std::remove_reference::type
    { 
        return x < y ? x : y; 
    }
    

    rev 2: KennyTM

    template 
    auto min(T x, U y)->decltype(x < y ? std::declval() : std::declval())
    { 
        return x < y ? x : y; 
    }
    

    rev 1: T and U must be default constructible

    template 
    auto min(T x, U y)->decltype(x < y ? T() : U())
    { 
        return x < y ? x : y; 
    }
    

    test:

    int main()
    {
       int x; int y;
       static_assert(std::is_same::value, "");
       return 0;
    }
    

    EDIT:

    I'm a bit surprised but it actually compiles with remove_reference.

提交回复
热议问题