/*
 * registration.hpp
 *
 * This file is part of Algorithms library toolkit.
 * Copyright (C) 2017 Jan Travnicek (jan.travnicek@fit.cvut.cz)

 * Algorithms library toolkit is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * Algorithms library toolkit is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Algorithms library toolkit.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Created on: Jan 26, 2019
 * Author: Jan Travnice
 */

#ifndef __REGISTRATION_HPP_
#define __REGISTRATION_HPP_

#include <functional>

namespace ext {

template < class T >
class Register {
	T data;

	std::function < void ( T ) > m_finish;
public:
	template < class InitCallback, class FinalizeCallback >
	Register ( InitCallback init, FinalizeCallback finish ) : m_finish ( std::move ( finish ) ) {
		data = init ( );
	}

	template < class InitCallback >
	Register ( InitCallback init ) : Register ( init, [] ( T ) { } ) {
	}

	Register ( const Register & ) = delete;

	Register ( Register && other ) noexcept : data ( std::move ( other.data ) ), m_finish ( std::move ( other.m_finish ) ) {
		other.m_finish = [] ( T ) { };
	}

	Register & operator = ( const Register & ) = delete;

	Register & operator = ( Register && other ) = delete;

	~Register ( ) {
		m_finish ( data );
	}
};

template < >
class Register < void > {
	std::function < void ( ) > m_finish;
public:
	template < class InitCallback, class FinalizeCallback >
	Register ( InitCallback init, FinalizeCallback finish ) : m_finish ( std::move ( finish ) ) {
		init ( );
	}

	template < class InitCallback >
	Register ( InitCallback init ) : Register ( init, [] ( ) { } ) {
	}

	Register ( const Register & ) = delete;

	Register ( Register && other ) noexcept : m_finish ( std::move ( other.m_finish ) ) {
		other.m_finish = [] ( ) { };
	}

	Register & operator = ( const Register & ) = delete;

	Register & operator = ( Register && other ) = delete;

	~Register ( ) {
		m_finish ( );
	}
};

} /* namespace ext */

#endif /* __REGISTRATION_HPP_ */
