What is difference between decltype(auto) and decltype(returning expr) as return type?

后端 未结 3 1180
慢半拍i
慢半拍i 2021-02-13 03:48

What is the difference between decltype(auto) and decltype(returning expression) as return type of a function (template) if expr used with

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-13 04:36

    Yes there is a difference. The first one will detect the return type based on the return expression in the body of the function.

    The second one will not also set the return type to the type of the expression inside decltype(), but will also apply expression sfinae on it. That means that if the expression inside decltype is not valid, the compiler will search for another valid overload. Whereas the first version will be a hard error.

    Take this example:

    template
    auto fun(T a) -> decltype(a.f()) { return a.f(); }
    
    template
    auto fun(T a) -> decltype(a.g()) { return a.g(); }
    
    struct SomeType {
        int g() { return 0; }
    };
    
    fun(SomeType{});
    

    This select the correct overload. Now if we replace decltype(expr) by decltype(auto), the compiler will not be able to select the correct overload, as there's nothing in the function signature that constrains what the type is supposed to be able to do.

提交回复
热议问题