开发者

C++ Template Specialization problem

I have a syntax similar to this:

template <class 开发者_开发百科P>
class Foo : public P
{
public:
    template <class T> Foo<P> & operator += (const T & v)
    { 
         /*grind*/
         return (*this);
    }
};

The problem starts when i try to specialize the operator += (outside of class Foo) for a particular type (int for example). I could do this:

template <class P> Foo<P>& Foo<P>::operator += ( const int & v)
{...}

but partial specialization is not possible and it is practically impossible to know the type of P at this point.

Is there any solution for this?

Thanks, Raxvan.


Instead of putting the logic in the operator+=, put it in a helper class, this can be partially specialized as required.


Node beat me to it, but here's some code that may help (though I'm using bare functions with overloading instead of a helper class):

template <class P>
class Foo : public P
{
public:
   template <class T> Foo<P> & operator += (const T & v)
   { 
      detail::implement_plus_equal( * this, v );
      return * this;
   }
};

namespace detail {
   template <class P>
   void implement_plus_equal(Foo<P> & f, int v)
   {
      /* grind an int */
   }

   template <class P, typename T>
   void implement_plus_equal(Foo<P> & f, T const & v)
   {
      /* grind a T */
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜