473,654 Members | 3,289 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 1975
<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
2122
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
1379
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
2160
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
2899
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
1951
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
1402
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
2511
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
2203
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
2284
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
8376
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8290
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
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8708
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
7307
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...
1
6161
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4149
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...
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1596
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.