C++11可变参数模板单例模式

单例模式

该示例代码采用C11标准,解决以下问题:

  1. 通过类模板函数实现不同类型单例;
  2. 单例类构造函数支持不同的个数;
  3. 消除代码重复

示例代码

.h文件如下:

cpp 复制代码
//C++11Singleton.h文件
#pragma once

template <typename T>
class Singleton
{
public:
	template<typename... Args>
	static T* Instance(Args&&... args)
	{
		if (m_pInstance == nullptr)
		{
			m_pInstance = new T(std::forward<Args>(args)...);
		}
		return m_pInstance;
	}

	static T* GetInstance()
	{
		if (m_pInstance == nullptr)
		{
			throw std::logic_error("the instance is not init,please initialize the instance first");
		}
		return m_pInstance;
	}

	static void DestorInstance()
	{
		delete m_pInstance;
		m_pInstance = nullptr;
	}

private:
	Singleton();
	virtual ~Singleton();
	Singleton(const Singleton&);
	Singleton& operator = (const Singleton&);
private:
	static T* m_pInstance;
};

.cpp文件如下:

cpp 复制代码
#include <iostream>
#include "C++11Singleton.h"
using namespace std;

template <class T> T* Singleton<T>::m_pInstance = nullptr;

struct A
{
    A(const string&) { cout << "lvalue" << endl; };
    A(string&& x) { cout << "rvalue" << endl; };
};

struct B
{
    B(const string&) { cout << "lvalue" << endl; };
    B(string&& x) { cout << "rvalue" << endl; };
};

struct C
{
    C(int x, double y) {};
    void Fun() { cout << "test" << endl; };
};

int main()
{
    string str = "bb";
    Singleton<A>::Instance(str);

    Singleton<B>::Instance(std::move(str));

    Singleton<C>::Instance(1,3.14);
    Singleton<C>::GetInstance()->Fun();

    Singleton<A>::DestorInstance();
    Singleton<B>::DestorInstance();
    Singleton<C>::DestorInstance();
   
    cin.get();
    return 0;
}

输出结果如下:

以上只是个示例,该单例非模式还不支持多线程调用。

相关推荐
Yurko1321 分钟前
【C语言】基本语法结构(上篇)
c语言·开发语言·学习
草莓熊Lotso31 分钟前
《C++ Stack 与 Queue 完全使用指南:基础操作 + 经典场景 + 实战习题》
开发语言·c++·算法
孤客网络科技工作室32 分钟前
Python - 100天从新手到大师:第五十七天获取网络资源及解析HTML页面
开发语言·python·html
武文斌7733 分钟前
复习总结最终版:计算机网络
linux·开发语言·学习·计算机网络
敲上瘾33 分钟前
单序列和双序列问题——动态规划
c++·算法·动态规划
ajassi200037 分钟前
开源 C++ QT QML 开发(二十二)多媒体--ffmpeg编码和录像
c++·qt·开源
帅大大的架构之路1 小时前
高级篇:Python脚本(101-150)
开发语言·python
reasonsummer2 小时前
【办公类-115-06】20250920职称资料上传04——docx复制、docx转PDF(课程表11个)
开发语言·windows·python·c#
栀寒老醑3 小时前
Python实现的服务器日志监控脚本
开发语言·python
星星点点洲3 小时前
PostgreSQL 15二进制文件
开发语言·设计模式·golang