简体   繁体   English

针对特定类型的模板 function 的特化

[英]Specialization of a template function for a specific type

Consider this function template returning the maximum of two type values:考虑这个 function 模板返回两个类型值的最大值:

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. PS:在这种情况下,我重载了 Entity 的const char*运算符以返回实体的名称和operator>进行比较。

Thanks in advance.提前致谢。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM