【编程基础の基础】CRTP+不定参数+单例模式

为便于编写不同派生类的单例模式(不同派生类的构造函数具有不相同的参数数目),故基于一般CRTP单例模式,编写了如下不定参数的CRTP单例模式。
如下为头文件。

// crtp.h
#include<memory>
#include<mutex>
template<class Derived>
class Singleton{
public:
    template<class ...Args>
    static Derived& get_Instance(const Args& ...args);
protected:
    Singleton()=default;
    ~Singleton()=default;
private:
    Singleton(Singleton&) =delete;
    static std::unique_ptr<Derived> _Instance;
    static std::once_flag _flag;
    
};

class derivedA:public Singleton<derivedA>
{
private:
    int p;
    friend class Singleton<derivedA>;
    derivedA(int);
public:
    int get_val() const;
    ~derivedA()=default;  
   

};

class derivedB:public Singleton<derivedB>
{
private:
    int p,q;
    friend class Singleton<derivedB>;
    derivedB(int,int);

public:
    std::pair<int,int> get_val() const;
    ~derivedB()=default;   

};

如下为实现。

#include "crtp.h"
template<class Derived>
template<class ...Args>
Derived& Singleton<Derived>::get_Instance(const Args& ...args){
        std::call_once(_flag,[](auto ...args){
            _Instance.reset(new Derived(args...));
        },args...);
        return *_Instance;
}

template<class Derived>
std::unique_ptr<Derived> Singleton<Derived>::_Instance=nullptr;

template<class Derived>
std::once_flag Singleton<Derived>::_flag;

derivedA::derivedA(int _val): p(_val)
{
}
int derivedA::get_val() const {return p;}


derivedB::derivedB(int _val1,int _val2): p(_val1),q(_val2)
{
}
std::pair<int,int> derivedB::get_val() const {return {p,q};}

int main(){
    derivedA& dA=derivedA::get_Instance(2);
    derivedB& dB=derivedB::get_Instance(2,3);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值