Alex
Alex

Reputation: 876

Specialization of a template function for a specific type

Consider this function template returning the maximum of two type values:

template<typename T>
T max(T a, T b)
{
   return a ? a > b : b;
} 

Is it possible to define a separate behavior for a user defined type the same way as we could do with classes? something which might look like this?

template<>
Entity max<Entity>(const Entity a, const Entity b)
{
   std::cout << "this is an entity" << std::endl;
   return a ? a > b : b;
} 

PS: In this case I overloaded the const char* operator of Entity to return the name of the entity and the operator> for the comparison.

Thanks in advance.

Upvotes: 1

Views: 55

Answers (1)

TonySalimi
TonySalimi

Reputation: 8437

Your code has some problems. I have fixed them in the below example code:

struct Entity
{
   bool operator >(const Entity & other)
   {
      return x > other.x;
   }
   int x = 0;
};

template<typename T>
T max(T a, T b)
{
   return a > b ? a : b;
}

template<>
Entity max(Entity a, Entity b)
{
   std::cout << "this is an entity" << std::endl;
   return a > b ? a : b;
}

int main()
{
   Entity e1;
   Entity e2;

   e1.x = 12;
   e2.x = 13;

   Entity max_en = max(e1, e2);
}

Upvotes: 2

Related Questions