C++ - What is the purpose of function template specialization? When to use it?

前端 未结 6 1971
北恋
北恋 2021-01-13 11:31

Learning C++, came upon function templates. The chapter mentioned template specialization.

  1. template <> void foo(int);

6条回答
  •  长发绾君心
    2021-01-13 12:06

    I personally can see no benefit from specializing a function template. Overloading it by either a different function template or a non-template function is arguably superior because its handling is more intuitive and it's overall more powerful (effectively by overloading the template, you have a partial specialization of the template, even though technically it's called partial ordering).

    Herb Sutter has written an article Why not specialize function templates? where he discourages specializing function templates in favour of either overloading them or writing them so that they just forward to a class template's static function and specializing the class template instead.

提交回复
热议问题