How to read the template partial specialization?

前端 未结 4 1495
不思量自难忘°
不思量自难忘° 2021-01-20 06:16

Suppose the following declaration:

template  struct MyTemplate;

The following definition of the partial specialization se

4条回答
  •  我在风中等你
    2021-01-20 06:38

    The correct reading of the specialisation is as follows:

    template  // a *type pattern* with a *free variable* `T` follows
    struct MyTemplate // `T*` is the pattern
    

    When the template is instantiated by MyTemplate, the argument is matched against the pattern, not the type variable list. Values of the type variables are then deduced from the match.

    To see this more directly, consider a template with two arguments.

    template 
    struct A;
    

    and its specialisation

    template 
    struct A;
    

    Now you can write the latter as

    template 
    struct A;
    

    (the variable list order is reversed) and this is equivalent to the previous one. Indeed, order in the list is irrelevant. When you invoke A it is deduced that T1=int, T2=double, regardless of the order of T1 and T2 in the template head.

    Further, you can do this

    template 
    struct A;
    

    and use it in A. It is now plainly clear that the type variable list has no direct correspondence with the actual template parameter list.

    Note: the terms "pattern", "type variable", "type pattern matching" are not standard C++ terms. They are pretty much standard almost everywhere else though.

提交回复
热议问题