Differences between template specialization and overloading for functions?

前端 未结 5 1687
误落风尘
误落风尘 2020-12-08 08:24

So, I know that there is a difference between these two tidbits of code:

template 
T inc(const T& t)
{
    return t + 1;
}

template &l         


        
5条回答
  •  天命终不由人
    2020-12-08 08:43

    Just to elaborate on the first point mentioned by litb in his answer. Specializations are only checked once overload resolution has actually selected a primary template. The result can lead to some surprises where a function is overloaded and has explicit specializations:

    template  void foo (T);  // Primary #1
    template <> void foo (int*);   // Specialization of #1
    
    template  void foo (T*); // Primary #2
    
    void bar (int * i)
    {
      foo(i);
    }
    

    When choosing which function to call, the following steps take place:

    1. Name lookup finds both primary templates.
    2. Each template is specialized and overload resolution attempts to select a best function based on conversions between the arguments and parameters.
    3. In thise case, there is no difference in the quality of the conversions.
    4. Partial ordering rules are then used to select the most specialized template. In this case that is the second parimary "foo(T*)".

    Only after these steps, when the best function has been selected will explicit specializations of the selected function be considered. (In this case primary #2 has none so none are considered).

    The only way to call the above explicit specialization here, is to actually use explicit template arguments in the call:

    void bar (int * i)
    {
      foo (i);  // expliit template argument forces use of primary #1
    }
    

    A good rule of thumb is to try to avoid having overloads that are also explicily specialized, as the resulting rules are pretty complex.

提交回复
热议问题