C/C++模板类
Posted mick_seu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C/C++模板类相关的知识,希望对你有一定的参考价值。
记录一个以前没见过的模板使用方法。
#include <iostream>
template <class T>
class Derived : public T
public:
Derived() std::cout << "Derived()" << std::endl;
~Derived() std::cout << "~Derived()" << std::endl;
;
class Base
public:
Base() std::cout << "Base()" << std::endl;
~Base() std::cout << "~Base()" << std::endl;
;
int main()
Derived<Base> db;
return 0;
输出:
Base()
Derived()
~Derived()
~Base()
用途:从未知的类T继承,然后在T的基础上附加一些必要的函数及变量。
利用这种模板函数,我们可以设计出单例。
#include <iostream>
#include <assert.h>
template <class T>
class SingletonWrapper : public T // 简单封装,添加一个flag
public:
~SingletonWrapper() is_destroyed_ = true;
static bool is_destroyed_;
;
template <class T>
bool SingletonWrapper<T>::is_destroyed_ = false;
template <class T>
class Singleton
public:
static T& Instance() // 接口函数
static SingletonWrapper<T> t; // 静态实例化
assert(!SingletonWrapper<T>::is_destroyed_);
return static_cast<T&>(t); // 返回 T&
static bool IsDestroyed() return SingletonWrapper<T>::is_destroyed_;
;
class Box
public:
void Init(const uint32_t size)
length_ = weigth_ = height_ = size;
void Show()
std::cout << "length: " << length_ << std::endl;
std::cout << "weigth: " << weigth_ << std::endl;
std::cout << "height: " << height_ << std::endl;
~Box() std::cout << "~Box()" << std::endl;
private:
uint32_t length_ = 0;
uint32_t weigth_ = 0;
uint32_t height_ = 0;
;
class BBox : public Singleton<BBox> // 风骚的操作,为BBox添加了两个静态函数用于单例的构造
public:
void Init(const uint32_t size)
length_ = weigth_ = height_ = size;
void Show()
std::cout << "length: " << length_ << std::endl;
std::cout << "weigth: " << weigth_ << std::endl;
std::cout << "height: " << height_ << std::endl;
~BBox() std::cout << "~BBox()" << std::endl;
private:
uint32_t length_ = 0;
uint32_t weigth_ = 0;
uint32_t height_ = 0;
;
int main()
// 1
Singleton<Box>::Instance().Init(10);
Singleton<Box>::Instance().Show();
// 2
BBox::Instance().Init(20);
BBox::Instance().Show();
std::cout << &BBox::Instance() << std::endl;
std::cout << &BBox::Instance().Instance().Instance() << std::endl;
return 0;
输出如下:
length: 10
weigth: 10
height: 10
length: 20
weigth: 20
height: 20
0x6021d0
0x6021d0
~BBox()
~Box()
可以发现 Singleton 类用来实现单例,我们有两种使用 Singleton 模板类的方式。
以上是关于C/C++模板类的主要内容,如果未能解决你的问题,请参考以下文章