簡體   English   中英

針對特定類型的模板 function 的特化

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

考慮這個 function 模板返回兩個類型值的最大值:

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>進行比較。

提前致謝。

你的代碼有一些問題。 我在下面的示例代碼中修復了它們:

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