针对特定类型的模板函数的专业化

问题描述 投票:1回答:1

考虑此函数模板返回两个类型值的最大值:

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

是否有可能像使用类一样为用户定义的类型定义单独的行为?看起来像这样的东西?

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

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

提前感谢。

c++ templates
1个回答
2
投票

您的代码有一些问题。我已经在下面的示例代码中修复了它们:

© www.soinside.com 2019 - 2024. All rights reserved.