Most important things about C++ templates… lesson learned

前端 未结 12 1441
暗喜
暗喜 2021-01-30 18:52

What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...common mistakes/oversight/assumptions

12条回答
  •  时光说笑
    2021-01-30 19:20

    From "Exceptional C++ style", Item 7: function overload resolution happens before templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called.

    template void f(T t) { ... }   // (a)
    template void f(T *t) { ... }  // (b)
    template<> void f(int *t) { ... } // (c)
    ...
    int *pi; f(pi); // (b) is called, not (c)!
    

    On top of Item 7:

    Worse yet, if you omit the type in template specialization, a different function template might get specialized depending on the order of definition and as a result a specialized function may or may not be called.

    Case 1:

    template void f(T t) { ... }  // (a)
    template void f(T *t) { ... } // (b)
    template<> void f(int *t) { ... }      // (c) - specializes (b)
    ...
    int *pi; f(pi); // (c) is called
    

    Case 2:

    template void f(T t) { ... }  // (a)
    template<> void f(int *t) { ... }      // (c) - specializes (a)
    template void f(T *t) { ... } // (b)
    ...
    int *pi; f(pi); // (b) is called
    

提交回复
热议问题