Re: Please help me write a functor template

From: Rob Williscroft (rtw_at_freenet.co.uk)
Date: 03/13/05


Date: 13 Mar 2005 17:33:58 GMT


 wrote in news:1110709181.652413.19730@o13g2000cwo.googlegroups.com in
comp.lang.c++:

>
> I understand that I could always settle for this syntax fairly easily:
>
> functor<bool, long, long> myFunctor;
> bool whether = myFunctor(4,5);

#include <iostream>
#include <ostream>

int function( int a, int b )
{
  std::cout << "function( " << a << ", " << b << " );\n";
  return 0;
}

/* declaration, no defenition
*/
template < typename F > struct functor;

/* Example, just the one specialization
*/
template < typename R, typename A1, typename A2 >
struct functor< R( A1, A2 ) >
{
  functor( R arg(A1, A2) ) : f( arg ) {}
  R operator () ( A1 a1, A2 a2 )
  {
    return f( a1, a2 );
  }

private:
  R (*f) ( A1, A2 );
};

int main()
{
  functor< int( int, int ) > f( function );
  return f( 1, 2 );
}

You will need to provide a specialization for each arity (number
of arguments) you want to support, also you might want to use
somthing to add `const &` to the paramiter types of the operator.

Untested code:

...

  R operator () (
      typename add_cref< A1 >::type a1,
      typename add_cref< A2 >::type a2
    )
  {
    return f( a1, a2 )
  }

...

template < typename T > struct add_cref
{
  typedef T const &type;
};
template < typename T > struct add_cref< T const & >
{
  typedef T const &type;
};
template < typename T > struct add_cref< T & >
{
  typedef T &type;
};

HTH.

Rob.

-- 
http://www.victim-prime.dsl.pipex.com/


Relevant Pages

  • [UNIX] ELFdump Crash when Analyzing Crafted ELF File
    ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: http://www.securiteam.com ... typedef unsigned char uint8_t; ... int GetArgs ... const char * const, ...
    (Securiteam)
  • Re: using CLASS::type
    ... typedef T type; ... int do_somethingconst ... 7.3.3p20 If a using-declaration uses the keyword typename and specifies ...
    (microsoft.public.vc.language)
  • Re: why use typedef instead of define?
    ... typedef int* INTP_TYPEDEF; ... INTP_MACRO const p2; ...
    (microsoft.public.vc.mfc)
  • Re: Interesting question on const.
    ... "const" type-qualify ... Now let say T is a typedef for "int *". ... const int object, can safely be changed to point to other ...
    (comp.lang.c)
  • Bypassing Personal Firewalls
    ... typedef SOCKET (int, int, int); ... typedef int (__stdcall *func_connect)(SOCKET, const struct sockaddr ... typedef HANDLE (LPCTSTR, DWORD, DWORD, ...
    (Bugtraq)