Raxvan
Raxvan

Reputation: 6505

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.

Upvotes: 2

Views: 120

Answers (2)

Jollymorphic
Jollymorphic

Reputation: 3530

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 */
   }
}

Upvotes: 1

Node
Node

Reputation: 3509

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

Upvotes: 1

Related Questions