Why is it not possible to overload class templates?

后端 未结 3 750
半阙折子戏
半阙折子戏 2020-12-01 13:28

Reading this question made me wonder: is there a technical reason for disallowing class templates overloads?

By overloading, I mean having several templates with the

3条回答
  •  青春惊慌失措
    2020-12-01 14:20

    Section 12.5 from Templates the Complete Guide (Amazon) contains this quote:

    You may legitimately wonder why only class templates can be partially specialized. The reasons are mostly historical. It is probably possible to define the same mechanism for function templates (see Chapter 13).

    In some ways the effect of overloading function templates is similar, but there are also some subtle differences. These differences are mostly related to the fact that the primary template needs to be looked up when a use is encountered. The specializations are considered only afterward, to determine which implementation should be used.

    In contrast, all overloaded function templates must be brought into an overload set by looking them up, and they may come from different namespaces or classes. This increases the likelihood of unintentionally overloading a template name somewhat.

    Conversely, it is also imaginable to allow a form of overloading of class templates. Here is an example:

    // invalid overloading of class templates
    template class Pair; 
    template class Pair; 
    

    However, there doesn't seem to be a pressing need for such a mechanism.

    Furthermore, the Design and Evolution of C++ (Amazon) contains this quote in section 15.10.3

    I therefore concluded that we needed a mechanism for "specializing" templates. This could be done either by accepting general overloading or by some more specific mechanism. I chose a specific mechanism because I thought I was primarily addressing irregularities caused by irregularities in C and because suggestions of overloading invariably creates a howl of protests. I was trying to be cautious and conservative; I now consider that a mistake. Specialization as originally defined was a restricted and anomalous form of overloading that fitted poorly with the rest of the language.

    Bold emphasis mine. I interpret this as saying that function overload resolution is more difficult to implement (and get right by users) than class specialization. So probably no real technical obstacles (similary for function template partial specialization) but an historical accident.

提交回复
热议问题