473,700 Members | 2,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Please help me write a functor template

Hello, I have been trying to write a functor template for a week now
and I'm just having tons of trouble because I don't understand an issue
that I guess is pretty basic to this task.

functor<bool (long, long)> myFunctor;
myFunctor = AFunctionOfThat Prototype;

To get that much is elementary because the template can just store a
(bool)(long,lon g) as a member variable in functor<T>. Here is the
problem:

bool whether = myFunctor(1,2);

How can I possibly ever utilize the individual result and parameter
type from the prototype in functor::operat or()? I have been poring over
several template libraries and I just can't see how they accomplish it
with partial specialization. After all, I can't debug the compiler
itself or look at preprocessor source to figure out what's happening.

I understand that I could always settle for this syntax fairly easily:

functor<bool, long, long> myFunctor;
bool whether = myFunctor(4,5);

And then use a typedef inside the template to make the prototype. But
the libraries I've seen don't have to settle for that. How is this
trick done??? If it matters, I'm using XCode. Thank you very much in
advance,

Yours,
Dan

Jul 23 '05 #1
8 1978
<da************ *@gmail.com> wrote...
Hello, I have been trying to write a functor template for a week now
and I'm just having tons of trouble because I don't understand an issue
that I guess is pretty basic to this task.

functor<bool (long, long)> myFunctor;
Perhaps you wanted

functor<bool(*) (long,long)> myFunctor;
myFunctor = AFunctionOfThat Prototype;

To get that much is elementary because the template can just store a
(bool)(long,lon g) as a member variable in functor<T>. Here is the
problem:

bool whether = myFunctor(1,2);

How can I possibly ever utilize the individual result and parameter
type from the prototype in functor::operat or()?
I am not sure what you mean here, but you need to implement that operator
to "utilize the individual result".
I have been poring over
several template libraries and I just can't see how they accomplish it
with partial specialization. After all, I can't debug the compiler
itself or look at preprocessor source to figure out what's happening.

I understand that I could always settle for this syntax fairly easily:

functor<bool, long, long> myFunctor;
bool whether = myFunctor(4,5);

And then use a typedef inside the template to make the prototype. But
the libraries I've seen don't have to settle for that. How is this
trick done??? If it matters, I'm using XCode. Thank you very much in
advance,


Well, if I understood your requirements and your comprehension of the
problem, you should be able to fill in the blanks here:

template<class F> class functor
{
F f; // that's something to what your functor
// delegates the functionlity
public:
functor& operator = (F ff) { ??? }
bool operator ()(long l1, long l2) { ??? }
};

The blanks I was talking about are indicated by ???

Of course, a parameterized constructor might be useful as well, so you
could write

functor<bool (*)(long,long)> myFunctor = AFunctionOfThat Prototype;

instead of using two statements.

Good luck!

V
Jul 23 '05 #2
wrote in news:11******** *************@o 13g2000cwo.goog legroups.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/
Jul 23 '05 #3
Thank you Victor and Rob. Peace.

Dan

Jul 23 '05 #4
Hmm. Couple of interesting things...

1. There seems to be no problem using const& like anything else, so I
haven't implemented add_cref.

2. When the prototype has no parameters I have to phrase it different
ways in different compilers.

template < typename R > class functor< R() > // this is fine in xcode,
breaks metrowerks
template < typename R > class functor< R(*)() > // vice versa

Weird...I'll keep exploring.

Dan

Jul 23 '05 #5
wrote in news:11******** *************@z 14g2000cwz.goog legroups.com in
comp.lang.c++:
Hmm. Couple of interesting things...

1. There seems to be no problem using const& like anything else, so I
haven't implemented add_cref.
Quite right too, never solve problems you don't have :).

2. When the prototype has no parameters I have to phrase it different
ways in different compilers.

template < typename R > class functor< R() > // this is fine in xcode,
breaks metrowerks
It should work, try: < R( void ) >.

Also its a good idea to give compiler version and platform as well
as vendor, somebody with the same or a similar configuration might
be able to provide a work around. Unfortunatly I don't have a
Metroworks compiler so I can't look for one myself.
template < typename R > class functor< R(*)() > // vice versa

Weird...I'll keep exploring.


Not really R(*)() is function-pointer, R() is function type
and this is one of the situations where a function type doesn't
decay to a function-pointer type, IOW it really shouldn't work.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 23 '05 #6
Well, since it isn't supposed to work I found a different way: if the
function returns a Homer, you just declare functor<Homer>, which is
reasonable to me as long as I can still declare functor<Homer (J,
Simpson)>. Following source is how I do it for 0 params. The emptiness
param is so it doesn't confuse the partial specialization with the
original definition.

(BTW Rob, putting void in the defintion seems to make no difference on
XCode 1.5 or MWCW 8. What compiler are you using?)

struct emptiness {};
template < typename F , typename E=emptiness > class functor;
// zero params alt syntax
template < typename R > class functor< R, emptiness>
{
typedef R(*pt)();
pt _pt;

public:
functor( ) : _pt( 0 ) {}
functor( pt arg ) : _pt( arg ) {}
R operator () ( ) const { return _pt( ); }
functor& operator = (pt arg) { _pt = arg; return *this; }
};

Jul 23 '05 #7
wrote in news:11******** **************@ l41g2000cwc.goo glegroups.com in
comp.lang.c++:
Well, since it isn't supposed to work I found a different way: if the
function returns a Homer, you just declare functor<Homer>, which is
reasonable to me as long as I can still declare functor<Homer (J,
Simpson)>. Following source is how I do it for 0 params. The emptiness
param is so it doesn't confuse the partial specialization with the
original definition.

(BTW Rob, putting void in the defintion seems to make no difference on
XCode 1.5 or MWCW 8. What compiler are you using?)

struct emptiness {};
template < typename F , typename E=emptiness > class functor;
// zero params alt syntax
template < typename R > class functor< R, emptiness>
{
typedef R(*pt)();
pt _pt;

public:
functor( ) : _pt( 0 ) {}
functor( pt arg ) : _pt( arg ) {}
R operator () ( ) const { return _pt( ); }
functor& operator = (pt arg) { _pt = arg; return *this; }
};


Looks good, but I'm not sure I see the need for the emptyness
paramiter why not just have the unspecialized version handle
0 paramiter case:

template < typename R > class functor
{
typedef R(*pt)();
pt _pt;

public:
functor( ) : _pt( 0 ) {}
functor( pt arg ) : _pt( arg ) {}
R operator () ( ) const { return _pt( ); }
functor& operator = (pt arg) { _pt = arg; return *this; }
};

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 23 '05 #8
Hmm...never even thought of that!

Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2129
by: CoolPint | last post by:
Can anyone explain how I can make the following function accept an default arguement for the last parameter, which should be an optional functor? template <typename T, typename FUNCTOR> void bsort(T * si, T * ei, FUNCTOR cmpfunc) { int k = 0; for (T * i = si; i < ei - 1; i++, k++) for (T * j = si; j < (ei-k-1) ; j++)
0
1381
by: CoolPint | last post by:
I am trying to write a generic heapsort (of course as a self-exercise) with Iterator interface: something like blow.... But I got into trouble finding out the Iterator to the Child node. If indexing was used, I could do something like child = hole * 2 + 1; but since only thing the function accepts are random access Iterators, how do I calculate the Iterator to the child node? template <typename Iterator, typename Functor> void...
3
2161
by: CoolPint | last post by:
I have implemented a generic priority queue below and tested it works fine, but I have one small problem I cannot understand. I have type parameter F which determines the priority so that users can instantiate in the following ways PQueue<int> pq1; PQueue<int, Functor> pq2; // where Functor is a name of user-defined class I also added another constructor to accept a function pointer so that
4
2901
by: daniel.w.gelder | last post by:
I wrote a template class that takes a function prototype and lets you store and call a C-level function, like this: inline string SampleFunction(int, bool) {..} functor<string (int, bool)> myFunctor = SampleFunction; string result = myFunctor(7, true); Works great thanks to the help from this group. Here's the guts so far for two-arity:
12
1962
by: aaragon | last post by:
Hi everyone, I'm trying to provide some external functionality to a class through a functor object defined by the user. The concept is as follows: template <class Functor> class ClassA { ... double evaluate(){
13
1406
by: Daniel T. | last post by:
typedef unsigned short u16; // may be different on your machine typedef unsigned char u8; // may be different on your machine // assume dst is zero initialized upon entry void packBits( u8* dst, const u16* src ) { dst |= src >1; dst |= src << 7; dst |= src >2; dst |= src << 6;
2
2514
by: Lionel B | last post by:
I have a function which takes a functor argument. I which to call it for a functor which is actually a class member; this works fine, using the mem_fun_ref and bind1st functions (see listing 1 below). Or, rather, it works fine as long as my member functor is const. The problem comes when I wish to use it for a *non*-const functor (see listing 2 below): *** Start listing 1 *************************************************** // test1.cpp
3
2207
by: alan | last post by:
Hello all, I'd like to know if there is a nice method of defining a functor creator which accepts an N-ary function and returns a functor based on that function. For example I have a function: template<class X, class Y, class Z> X function(Y, Z); Passing it to the functor creator will give a functor equivalent to: template<class X, class Y, class Z>
2
2287
by: aaragon | last post by:
Hi guys, Is there a way to return a functor from a recursive call that takes different paths? Let's say that I have a tree structure like: root | first child ---- nextSibling ----nextSibling ----nextSibling ---->0 | |
0
8642
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9066
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8916
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7802
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5899
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4400
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4652
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3083
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2383
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.