Template specialisation where templated type is also a template

前端 未结 2 2030
既然无缘
既然无缘 2021-01-05 20:43

I\'ve created a small utility function for string conversion so that I don\'t have to go around creating ostringstream objects all over the place

template<         


        
2条回答
  •  长情又很酷
    2021-01-05 21:20

    Don't specialize the template, but overload it. The compiler will figure out what function template to take by ordering them according to their specialization of their function parameter types (this is called partial ordering).

    template
    inline string ToString(const std::pair& x) {
        std::ostringstream o;
        if (!(o << "[" << x.first << "," << x.second << "]"))
            throw BadConversion(string("ToString(pair)"));
        return o.str();
    }
    

    In general, partial ordering will result in exactly what you expect. In more detail, consider having these two functions

    template void f(T);
    template void f(pair);
    

    Now, to see whether one is at least as specialized as the other one, we test the following for both function templates:

    1. chose some unique type for each template parameter, substitute that into the function parameter list.
    2. With that parameter list as argument, make argument deduction on the other template (make a virtual call with those arguments to that other template). If the deduction succeeds and there is no conversion required (adding const is such one).

    Example for the above:

    1. substituting some type X1 into T gives us some type, call it X1. argument deduction of X1 against pair won't work. So the first is not at least as specialized as the second template.
    2. substituting types Y1 and Y2 into pair yields pair. Doing argument deduction against T of the first template works: T will be deduced as pair. So the second is at least as specialized as the first.

    The rule is, a function template A is more specialized than the other B, if A is at least as specialized as B, but B is not at least as specialized as A. So, the second wins in our example: It's more specialized, and it will be chosen if we could in principle call both template functions.

    I'm afraid, that overview was in a hurry, i only did it for type parameters and skipped some details. Look into 14.5.5.2 in the C++ Standard Spec to see the gory details. g

提交回复
热议问题