Overloaded member functions for a specific specialization

I have a tPoint class that will be implemented with different base types, so

template<typename T>class tPoint{
   T x;
   T y;
public:
   void Set(T ix, T iy){x=ix;y=iy;}
};

When the type T is int, tPoint<int>I want a special Set (float, float) so that I can round the values ​​to the destination.

I thought that by specialization I could:

template<> void tPoint<int>::Set(float ix,float iy){x=ix+.5; y=iy+.5;}

Thus, the compiler complains that there is no corresponding function in the class definition.

But if I declare Set (float, float) in the class, then it says it is already defined (when it compiles for T = float)

I hope I made it clear what a clean approach would be, or am I doing something wrong? thank!

+5
source share
5 answers

, :

template<> class tPoint<int>{
   int x;
   int y;
public:
   void Set(int ix, int iy){x=ix;y=iy;}
   void Set(float ix, float iy){x = ix+0.5; y = iy+0.5;}
};
+5

, , T, int, float.

, , T, typename template, Set.

, Point<int>, one Set, int. Point<T> Set(T,T).

Set, Set , :

template <typename T>
class Point
{
public:
  template <typename Num>
  void Set(Num x, Num y);
};

, .


, float, double long double... .

- :

template <typename Integral>
template <typename Num>
void Point<Integral>::Set(Num x, Num y)
{
  this->x = long double(x) + 0.5;
  this->y = long double(y) + 0.5;
}

int al, , . , , .

, , Point<float>, , . std::numeric_limits<T> a is_integer, , .

template <typename T>
template <typename Num>
void Point<T>::Set(Num x, Num y)
{
  if (std::numeric_limits<T>::is_integer &&
     !std::numeric_limits<Num>::is_integer)
  {
    this->x = x + 0.5;
    this->y = y + 0.5;
  }
  else
  {
    this->x = x;
    this->y = y;
  }
  }
}

, if , ... , , if ;)

+3

boost enable_if, float float.

0

:

template<typename T>class tPoint{
   T x;
   T y;
public:
   void Set(T ix, T iy) { set_impl(boost::type<T>(), x, y); }
private:
   void set_impl(boost::type<int>, float ...);
   template<typename U>
   void set_impl(boost::type<U>, T ...);
};
0

Set() . , float.

0

All Articles