Why is template parameter pack used in a function argument type as its template argument list not able to be explicit specified

前端 未结 5 627
失恋的感觉
失恋的感觉 2020-12-28 12:55

I have the following piece of code:

template 
struct AAA{};

template
void f(AAA *) {}

int          


        
5条回答
  •  心在旅途
    2020-12-28 13:00

    For you are using typename ...Args, the compiler doesn't know if int, int are all the template parameters in use or more are available by deducing the function argument. Therefore the function isn't instantiated yet and the compiler goes on trying to deduce all the other possible parameters for the parameter pack from the function arguments.

    In other terms, this works:

    f(new AAA);
    

    Because you are saying that the first parameter is int, but the compiler expects a parameters list and goes on trying to find more and more parameters greedily from the function argument, then it instantiates the function template.

    More or less the same happens in your case, but the compiler cannot deduce anything from nullptr_t for function arguments doesn't match. It expects a pointer to an A<...>, that is not the case when you pass in nullptr.
    This would work instead:

    template 
    struct AAA{};
    
    template
    void f(AAA *) {}
    
    int main() {
        f(nullptr);
    }
    

    Because the compiler knows template arguments are two and you are providing all of them, there is nothing to deduce and the function can be instantiated. It also makes much more sense, for AAA accepts only two template parameters, so a parameter pack for f seems useless here.

提交回复
热议问题