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

后端 未结 3 1178
慢半拍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

    decltype(auto) is used to

    • Forward return type in generic code, you don't want to type a lot of duplicate thing

      template
      decltype(auto) foo(Func f, Args&&... args) 
      { 
          return f(std::forward(args)...); 
      }
      
    • Delay type deduction, as you can see in this question, compilers have some problem with out decltype(auto)

      • This doesn't work well as you can see with g++ and clang++

        template struct Int {};
        constexpr auto iter(Int<0>) -> Int<0>;
        
        template constexpr auto iter(Int) -> decltype(iter(Int{}));
        
        int main(){
          decltype(iter(Int<10>{})) a;
        }
        
      • This works well as you can see here:

        template struct Int {};
        
        constexpr auto iter(Int<0>) -> Int<0>;
        
        template
        constexpr auto iter(Int) -> decltype(auto) {
          return iter(Int{});
        }
        
        int main(){
          decltype(iter(Int<10>{})) a;
        }
        

    decltype(expr):

    • applies SFINAE while decltype(auto) is not

提交回复
热议问题