Variadic template recursive return type deduction compilation error

后端 未结 3 1283
一整个雨季
一整个雨季 2021-01-05 03:38

Why the code below does not compile?

template 
T sum(T t){
    return t;
}

template 
auto sum(T t, U... u         


        
3条回答
  •  不知归路
    2021-01-05 04:35

    Quoted from [basic.scope.pdecl]:

    The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any)

    The declaration of the second function template is complete after the trailing return type decltype(t + sum(u...)). So, when parsing decltype(t + sum(u...)), the second template is not in scope yet, and the compiler can only see the first template which does not match the call.

    One possible fix:

    template 
    struct ReturnType;
    
    template 
    struct ReturnType {
      typedef T Type;
    };
    
    template 
    struct ReturnType {
      typedef typename ReturnType::Type Type_;
      typedef decltype(std::declval() + std::declval()) Type;
    };
    
    template 
    T sum(T t){
        return t;
    }
    
    template 
    typename ReturnType::Type sum(T t, U... u) {
        return t + sum(u...);
    }
    

提交回复
热议问题