实例化的c++模板细节

c++ template specifics to instantiation

本文关键字:细节 c++ 实例化      更新时间:2023-10-16

我正在编写一个代码,该代码使用模板来支持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,在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