实例化的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
,在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
相关文章:
- 'using namespace'实现细节的便捷方法(仅标头库)?
- Clang 错误 – 编译器错误或缺少一些细节?
- 用于隐藏结构细节的迭代器适配器
- 将C++项目迁移到 Java,保护实现细节
- Deque实施细节
- 关于为什么Windows的.dll不适用于Linux的细节
- 是否有一种更干净的方法来揭示实施细节进行测试
- 如何在C++共享库中隐藏业务对象的实现细节并提供接口
- 接口,在C++中隐藏具体的实现细节
- 我可以抽象出模板类的具体细节吗
- 无锁单写多读列表的实现细节
- 与朋友在课堂上进行内部功能,以隐藏公共细节
- 无法找出赛格故障,提供了很多细节
- 为初学者澄清C++中类定义和实现的一些细节
- C# 与C++:继承细节
- 在它的核心,如何实现提升元组(在提升标头中没有所有额外的细节)
- 我如何理解这个生成文件规则的细节
- CRTP 铸造细节
- 实例化的c++模板细节
- 图像拼接细节与OpenCV