473,594 Members | 2,655 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Allowing a functor or a function to be stored in a class

In the C++ STL, there are various places where you can call a function that
takes a functor as a parameter. This functor may be either a function object or
a function pointer. For instance, if you have a vector<char> and call for_each
on it, both of the methods below would be valid:

#include <iostream>
#include <vector>
using namespace std;

struct MyFunctionObjec t
{
void operator ()(char a) {cout << a;};
};
void myFunction(char a) {cout << a;}

int main()
{
vector<char> v;
//fill it . . .
for_each(v.begi n(), v.end(), (MyFunctionObje ct()));
for_each(v.begi n(), v.end(), &myFunction) ;
return 0;
}

My question pertains to a similar issue: how do I cause the same to occur in a
class template? I would like my template to look like this:

template <typename CompT>
class WhyWontThisWork
{
CompT m_comparator;
public:
WhyWontThisWork (CompT cmpIn) : m_comparator(cm pIn) {}
void doThis(char a, char b) { if (m_comparator(a , b)) cout << "WIN"; }
};

Can I actually do this in C++ without writing an inordinate amount of code? If
so, how?

- JFA1
Jul 23 '05 #1
11 1375
James Aguilar wrote:

My question pertains to a similar issue: how do I cause the same to occur in a
class template? I would like my template to look like this:

template <typename CompT>
class WhyWontThisWork
{
CompT m_comparator;
public:
WhyWontThisWork (CompT cmpIn) : m_comparator(cm pIn) {}
void doThis(char a, char b) { if (m_comparator(a , b)) cout << "WIN"; }
};

Can I actually do this in C++ without writing an inordinate amount of code? If
so, how?


This works just fine. What problem did you encounter?

struct Comp
{
bool operator()(char a, char b) const { return a == b; }
};

int main()
{
Comp comp;
WhyWontThisWork <Comp> cmp(comp);
cmp.doThis('a', 'b');
cmp.doThis('a', 'a');
return 0;
}

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #2
James Aguilar wrote:
In the C++ STL, there are various places where you can call a function that
takes a functor as a parameter. This functor may be either a function object or
a function pointer. For instance, if you have a vector<char> and call for_each
on it, both of the methods below would be valid:

#include <iostream>
#include <vector>
using namespace std;

struct MyFunctionObjec t
{
void operator ()(char a) {cout << a;};
};
void myFunction(char a) {cout << a;}

int main()
{
vector<char> v;
//fill it . . .
for_each(v.begi n(), v.end(), (MyFunctionObje ct()));
for_each(v.begi n(), v.end(), &myFunction) ;
return 0;
}

My question pertains to a similar issue: how do I cause the same to occur in a
class template? I would like my template to look like this:

template <typename CompT>
class WhyWontThisWork
{
CompT m_comparator;
public:
WhyWontThisWork (CompT cmpIn) : m_comparator(cm pIn) {}
I don't understand 'WhyWontThisWor k' bit of it.
void doThis(char a, char b) { if (m_comparator(a , b)) cout << "WIN"; }
};

Can I actually do this in C++ without writing an inordinate amount of code?
What's inordinate?

I don't see you even attempting to use your template. How can we continue
the discussion without you even trying?
If
so, how?


What book are you reading that doesn't explain templates? What section of
the FAQ regarding questions about some code that doesn't work don't you
understand? Am I using overly long sentences?

V
Jul 23 '05 #3

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:IP******** **********@news read1.mlpsca01. us.to.verio.net ...

I don't see you even attempting to use your template. How can we continue
the discussion without you even trying?


OK.

//=== CODE ===
#include <iostream>

using namespace std;

template <typename CompT>
class Test
{
CompT m_comparator;
public:
Test(CompT cmpIn) : m_comparator(cm pIn) {}
void doThis(char a, char b) { if (m_comparator(a , b)) cout << "WIN"; }
};

class TestFunctionObj ect
{
public:
bool operator ()(char a, char b) {return a < b;}
};

bool testFunction(ch ar a, char b)
{
return a < b;
}

int main()
{
Test a(&testFunction );
Test b((TestFunction Object()));

a.doThis('a', 'b');
b.doThis('a', 'b');

return 0;
}
//=== CODE ===

For obvious reasons, this code does not compile. I didn't provide template
types for a or b in main. But that is really the question I am asking: is it
possible for me to have a class that can take a function pointer or a function
object in the constructor and treat them the same way (i.e. store them for later
use in another function)? If so, what is the type I need to use to replace
CompT?

- JFA1
Jul 23 '05 #4
James Aguilar wrote:
Test(CompT cmpIn) : m_comparator(cm pIn) {}
If so, what is the type I need to use to replace
CompT?


Since CompT is the type of the argument that you're going to pass to the
constructor, that's the type you should specify. That's also why the
standard library provides the template functions bind1st() and bind2nd()
in addition to the template classes binder1st and binder2nd.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #5
James Aguilar wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:IP******** **********@news read1.mlpsca01. us.to.verio.net ...
I don't see you even attempting to use your template. How can we continue
the discussion without you even trying?

OK.

//=== CODE ===
#include <iostream>

using namespace std;

template <typename CompT>
class Test
{
CompT m_comparator;
public:
Test(CompT cmpIn) : m_comparator(cm pIn) {}
void doThis(char a, char b) { if (m_comparator(a , b)) cout << "WIN"; }
};

class TestFunctionObj ect
{
public:
bool operator ()(char a, char b) {return a < b;}
};

bool testFunction(ch ar a, char b)
{
return a < b;
}

int main()
{
Test a(&testFunction );
Test b((TestFunction Object()));

a.doThis('a', 'b');
b.doThis('a', 'b');

return 0;
}
//=== CODE ===

For obvious reasons, this code does not compile.


Well, DUH!
I didn't provide template
types for a or b in main. But that is really the question I am asking: is it
possible for me to have a class that can take a function pointer or a function
object in the constructor and treat them the same way (i.e. store them for later
use in another function)? If so, what is the type I need to use to replace
CompT?


Of course not. "Test" is a template. It needs an argument. The class
'TestFunctionOb ject' and the function 'testFunction' have different types.
You cannot expect your 'Test' template to become one and the same if you
instantiate it with two different types, now, can you?

You can always make your 'Test' class take a functor but to use, say,
functions with it you'd have to provide a separate object. Example:

struct myFunctor_base {
virtual void operator() const (char a, char b) = 0;
};

struct function_to_myF unctor_adapter : myFunctor_base {
void (*pfunc)(char,c har);
function_to_myF unctor_adapter( void (*p)(char,char) ) : pfunc(p) {}
void operator()(char a, char b) const {
return pfunc(a,b);
}
};

struct myFunctor : myFunctor_base {
void operator()(char ,char) const; // implemented elsewhere
};

class Test {
myFunctor_base const& f;
public:
Test(myFunctor_ base const& ff) : f(ff) {}
void doThis(char a, char b) { f(a,b); }
};

void myFunction(char a, char b);

int main() {
Test a = Test(myFunctor( ));
Test b = Test(function_t o_myFunctor_ada pter(myFunction ));
a.doThis('a', 'b');
b.doThis('a', 'b');
}

Now, this probably constitutes (how did you put it?) inordinate amount
of code, but that's essentially how you can do it.

V
Jul 23 '05 #6

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:tq******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...

Now, this probably constitutes (how did you put it?) inordinate amount
of code, but that's essentially how you can do it.


That's exactly how I put it, and yeah, it meets the criteria. I appreciate your
writing that code -- I probably wouldn't have if someone was asking me the same
question.

I take it that the solution to my problem is thus to choose one or the other
(function pointers or function objects) and stick with it, and not try to make
my stuff compatible with both?

- JFA1
Jul 23 '05 #7
Victor Bazarov wrote:

template <typename CompT>
class Test
{
CompT m_comparator;
public:
Test(CompT cmpIn) : m_comparator(cm pIn) {}
void doThis(char a, char b) { if (m_comparator(a , b)) cout << "WIN"; }
};
bool testFunction(ch ar a, char b)
{
return a < b;
}


You can always make your 'Test' class take a functor but to use, say,
functions with it you'd have to provide a separate object.


It works as is, but you have to get the type of the template argument right:

Test<bool (*const)(char,c har)> wrap(testFuncti on);

The reason that the standard library templates need wrapper classes for
function pointers is to provide the nested typedefs result_type and the
various argument_types. The TR1 function adaptors don't need these
typedefs, so, like Test, they can be used with raw function pointers.
(See my article in the upcoming May issue of CUJ).

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #8
Victor Bazarov wrote:

Test a = Test(myFunctor( ));
Test b = Test(function_t o_myFunctor_ada pter(myFunction ));


Oh, I see, you're solving a different problem from the one I was
solving. The original template can be instantiated with various types;
if you need a single type that can hold different types of target
objects you need TR1's template class "function":

function<bool(c har,char)> fp;
fp = TestFunctionObj ect();
fp = testFunction;

(Okay, you have to add "typedef bool result_type" to TestFunctionObj ect
to get this to compile with normal C++ compilers)

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #9
"Pete Becker" <pe********@acm .org> wrote...
Victor Bazarov wrote:

Test a = Test(myFunctor( ));
Test b = Test(function_t o_myFunctor_ada pter(myFunction ));
Oh, I see, you're solving a different problem from the one I was solving.
The original template can be instantiated with various types; if you need
a single type that can hold different types of target objects you need
TR1's template class "function":

function<bool(c har,char)> fp;
fp = TestFunctionObj ect();
fp = testFunction;


This is neat. I didn't know that. How many compilers support this?
Is 'function' template class part of 'std'? Which header to include?
(Okay, you have to add "typedef bool result_type" to TestFunctionObj ect to
get this to compile with normal C++ compilers)


"Normal"? What do you mean? Is it already supported?

Thanks.

V
Jul 23 '05 #10

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

Similar topics

8
3494
by: lok | last post by:
i have a class: template <class T1, class T2> class CPairMapping { public: typedef std::pair<T1, T2> ValuePair_t; typedef std::vector<ValuePair_t> ValueList_t; typedef std::binary_function< ValuePair_t, ValuePair_t, bool> ValuePair_IsLess; void SortAscend(const ValuePair_IsLess& isLess_) {
3
2158
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
8
2691
by: Amit | last post by:
Hello all. If I want to use an object both as a Functor and also, if I pass a function pointer, how can it be done ? For instance, I have something like this template< typename Iter, typename Predicate> class MyOperation: public std::binary_function<Iter, Iter,bool> { public: bool operator() (const Iter &val1, const Itr &val2) const {
4
2895
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
1944
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(){
2
2509
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
1
2802
by: BSand0764 | last post by:
I'm getting an error that I can't seem to resolve. When I compile the Functor related logic in a test program, the files compile and execute properly (see Listing #1). However, when I incorporate the same logic within my simulation, the class that implements the functor logic has problems compiling. I get the following errors: -- Building myTest.cpp --
3
2202
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
2279
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
7941
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
7874
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
8368
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...
1
8000
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8231
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
6652
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
5738
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
5404
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
3854
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...

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.