#pragma once
//https://github.com/jose-villegas/VCTRenderer
#include <iostream>
#include<memory>
#include<string>
using namespace std;
template<class T> class SingleActive
{
public:
static void ResetActive();
/// <summary>
/// Sets this instance as active.
/// </summary>
virtual void SetAsActive();
/// <summary>
/// Return whether this instance is the one marked as active.
/// </summary>
/// <returns></returns>
bool IsActive();
/// <summary>
/// Returns the active instance;
/// </summary>
/// <returns></returns>
static std::unique_ptr<T> &Active();
protected:
/// <summary>
/// The current instance marked as active
/// </summary>
static std::unique_ptr<T> current;
~SingleActive();
};
template<class T>
std::unique_ptr<T> SingleActive<T>::current = nullptr;
template<class T>
SingleActive<T>::~SingleActive()
{
// release ownership but don't delete
if (static_cast<T *>(this) == current.get())
{
current.release();
}
}
template <class T>
void SingleActive<T>::ResetActive()
{
current.release();
current.reset(static_cast<T *>(nullptr));
}
template<class T>
void SingleActive<T>::SetAsActive()
{
current.release();
current.reset(static_cast<T *>(this));
}
template <class T>
bool SingleActive<T>::IsActive()
{
return current.get() == static_cast<T *>(this);
}
template<class T>
std::unique_ptr<T> &SingleActive<T>::Active()
{
return current;
}
/*
class student :public SingleActive<student> {
public:
string name;
string id;
student(string n, string i) :name(n), id(i) {}
};
int main()
{
unique_ptr<student> s1(new student("Alice", "123"));
unique_ptr<student> s2(new student("Alice2", "123"));
unique_ptr<student> s3(new student("Alice3", "123"));
s1->SetAsActive();
//s2->SetAsActive();
static auto&ss = student::Active();
cout << " " << ss->name << " " << ss->id << endl;
while (1);
}
*/
SingleActive
最新推荐文章于 2023-04-04 10:07:44 发布