Specialize a template with a template

后端 未结 2 706
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 06:31

I have a (free) function template that looks like this

template 
T get();

I now want to specialize this function for a class,

2条回答
  •  半阙折子戏
    2021-01-21 07:34

    What you're doing is called partial specialization of function template. But partial specialization of function template is not allowed. Overloading of function template is allowed, but in this case, it is not possible either, as the function has only return type, and overloading on return type is not allowed.

    So the solution is this:

    namespace details
    {
         template 
         struct worker
         {
             static T get();
         };
    
         template  //partial specialization of class is allowed
         struct worker>
         {
             static foo get();
         };
    
    }
    
    template 
    T get()
    {
      return details::worker::get();
    }
    

    You could also use overloads if you define them to take one argument so as to make overload valid:

    namespace details
    {
         template 
         static T get(T*); 
    
         template  
         static foo get(foo*); //now the overload is valid
    
    }
    
    template 
    T get()
    {
      return details::get(static_cast(0));
    }
    

    Note that the argument static_cast(0) is used to help the compiler to select the correct overload. If T is other than foo, then the first overload will be selected as the type of the argument passed to it will be T* as opposed to foo*. If T is foo, then the second overload will be selected by the compiler because it is more specialized, and can accept the argument passed to it which is foo* in this case.

提交回复
热议问题