特定类型的模板函数的专用化

Specialization of a template function for a specific type

本文关键字:函数 专用 类型      更新时间:2023-10-16

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

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

提前谢谢。

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

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