Jump to content
Moopler Closing Read more... ×
Moopler
Guest yuri

Snippet TSingleton - Reorganized

Recommended Posts

Guest yuri

Did not test this yet. There could be an error for pointer not being initialized in the constructor. Since it is generic class, I think it could be auto assigned to pointer (idk) if not then just do pointer = address in constructor? after delete. The "delete this" may not be right action, so let me know what you all think. I think you can explictly use template and have a class be generic still but the typename would need to be set to either int, long, dword or whatever the pointer (0x02XXXXX) is written to.

#pragma once

template <class T, typename address>
class TSingleton
{
public:
    TSingleton();
    ~TSingleton();
    static T* getInstance();
    static bool isInitialized();
private:
    address pointer;
};
#include "TSingleton.h"

/**
* \brief explicit instantiation for dynamic usage. Add or remove
*/
template TSingleton<class T, int>;


template<class T, typename address>
TSingleton<T, address>::TSingleton()
{
    delete this;
}


template<class T, typename address>
TSingleton<T, address>::~TSingleton()
{
    delete this;
}


template<class T, typename address>
T * TSingleton<T, address>::getInstance()
{
    return *reinterpret_cast<T**>(pointer);
}


template<class T, typename address>
bool TSingleton<T, address>::isInitialized()
{
    return getInstance() != nullptr;
}

 

Edited by yuri

Share this post


Link to post
#pragma once

template <typename T, int addy>
class TSingleton
{
	TSingleton() = delete;
	~TSingleton() = delete;
public:
	static T* GetInstance()
	{
		return *reinterpret_cast<T**>(addy);
	}

	static bool IsInitialized()
	{
		return GetInstance() != nullptr;
	}
};

This is more like it

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×