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

前端 未结 6 1937
北恋
北恋 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 11:56

    You can use specialization when you know for a specific class the generic method could be efficient.

    template
    void MySwap(T& lhs, T& rhs)
    {
        T tmp(lhs);
        lhs  = rhs;
        rhs  = tmp;
    }
    

    Now for vectors my swap will work, but is not very effecient. But I also know that std::vector implements its own swap() method.

    template<>
    void MySwap(std::vector& lhs,std::vector& rhs)
    {
        lhs.swap(rhs);
    }
    

    Please don;t compare to std::swap which is a lot more complex and better written. This is just an example to show that a generic version of MySwap() will work but is may not always be efficient. As a result I have shown how it can be made more efficient with a very specific template specialization.

    We can also of course use overloading to achieve the same effect.

    void MySwap(std::vector& lhs,std::vector& rhs)
    {
        lhs.swap(rhs);
    }
    

    So the question if why use template specialization (if one can use overloading). Why indeed. A non template function will always be chosen over a template function. So template specialization rules are not even invoked (which makes life a lot simpler as those rules are bizarre if you are not a lawyer as well as a computer programmer). So let me thing a second. No can't think of a good reason.

提交回复
热议问题