簡體   English   中英

實例化的C ++模板細節

[英]c++ template specifics to instantiation

我正在編寫一個代碼,該代碼使用模板來支持int數據類型和char *數據類型。 可以說

struct node {
    KeyType key;
    struct node *next;
};

而且這是排序的鏈表節點,因此無論何時插入節點,我都必須進行比較。 為此,我創建了一個頭文件comparison.h ,其中定義了比較操作,例如

LT(a,b)..
GT(a,b)..

當我使用node<int>我將LT(a, b) as a<b定義LT(a, b) as a<b而在node<char*> strncmp(a, b, SIZE) (使用宏我切換定義)所以有什么辦法通過這種方式,我最小化了此comparison.h 使用模板時,使用比較或特定於數據類型的特定操作的更好方法應該是什么?

使用模板專業化 例如:

#include <iostream>
#include <string>
using namespace std;

template <class T>
class node {
    T data;
  public:
    node(){}
    static bool GT (const T& first, const T& second);
};

template <class T>
bool node<T>::GT(const T &first, const T &second)
{
    std::cout << "general use" << std::endl;
    return first > second;
}

template <>
bool node<string>::GT(const string &first, const string &second)
{
    std::cout << "called from a string" << std::endl;
    return first.compare(second)>0;
}

int main () {
  std::cout << node<int>::GT(10,20) << std::endl;
  std::cout << node<string>::GT("Hello","World") << std::endl;
  return 0;
}

輸出將是:

general use
0
called from a string
0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM