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;
}

输出结果如下:

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

相关推荐
故事不长丨6 小时前
C#定时器与延时操作的使用
开发语言·c#·.net·线程·定时器·winform
hefaxiang6 小时前
C语言常见概念(下)
c语言·开发语言
“αβ”6 小时前
MySQL表的操作
linux·网络·数据库·c++·网络协议·mysql·https
欧阳天风6 小时前
js实现鼠标横向滚动
开发语言·前端·javascript
十五年专注C++开发7 小时前
Asio2: 一个基于 Boost.Asio 封装的高性能网络编程库
网络·c++·boost·asio·asio2
gcfer7 小时前
CS144 中的C++知识积累
c++·右值引用·智能指针·optional容器
yue0087 小时前
C# Directory的用法介绍
开发语言·c#
雨落秋垣7 小时前
手搓 Java 的用户行为跟踪系统
java·开发语言·linq
Bona Sun8 小时前
单片机手搓掌上游戏机(二十)—pico运行doom之编译环境
c语言·c++·单片机·游戏机
爱丽_8 小时前
深入理解 Java Socket 编程与线程池:从阻塞 I/O 到高并发处理
java·开发语言