/*
 * The UDS Collection
 * Copyright (C) 2000, 2001  Julian v. Bock
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *	(See file COPYING for more information)
 */

#ifndef _uds_flex_func_hh
#define _uds_flex_func_hh


namespace uds
{

template < class Ret, class Arg >
class flex_func_base
{
public:
	virtual
	~flex_func_base() {}
	
	virtual flex_func_base*
	Clone() = 0;
	
	virtual Ret
	operator () ( Arg ) = 0;
};

template < class Op >
class flex_func_t : public flex_func_base< typename Op::result_type,
	typename Op::argument_type >
{
public:
	flex_func_t( Op o ) : op( o ) {}

	virtual
	~flex_func_t() {}
	
	virtual flex_func_t< Op >*
	Clone() { return new flex_func_t< Op >( *this ); }
	
	virtual typename Op::result_type
	operator () ( typename Op::argument_type x ) { return op( x ); }
	
private:
	Op op;
};

template < class Ret, class Arg >
class flex_func_t< Ret ( * )( Arg ) > : public flex_func_base< Ret, Arg >
{
public:
	typedef  Ret ( *Op )( Arg );
	
	flex_func_t( Op o ) : op( o ) {}

	virtual
	~flex_func_t() {}
	
	virtual flex_func_t< Op >*
	Clone() { return new flex_func_t< Op >( *this ); }
	
	virtual Ret
	operator () ( Arg x ) { return op( x ); }
	
private:
	Op op;
};

template < class Ret, class Arg >
class flex_func
{
public:
	template < class Op >
	flex_func( Op op ) : ff( new flex_func_t< Op >( op ) ) {}
	
	flex_func( const flex_func& rhs ) : ff( rhs.ff->Clone() ) {}
	
	~flex_func() { delete ff; }
	
	Ret
	operator () ( Arg x ) { return ( *ff )( x ); }
	
private:
	flex_func_base< Ret, Arg >* ff;
};

}

#endif // _uds_flex_func_hh
