473,757 Members | 10,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on usage of functional object.

I've got following code test C++'s functor. For the sake of
easy-reading, I omit some declearations.

#include <algorithm>
#include <functional>

using namespace std;

template <typename Tclass Sum{
public:
Sum(T i=0):sum(i){};
inline void operator () (T x){
sum += x;
}
inline T output() const{
return sum;
}

private:
T sum;
};

int main( void ){
vector<intvec(1 0, 1);

Sum<intsum;

sum = for_each(vec.be gin(), vec.end(), Sum<int>()); .......(1)
sum = for_each(vec.be gin(), vec.end(), sum); .........(2)
sum = for_each(vec.be gin(), vec.end(), sum.operator()( int) ); ...(3)

cout << sum.output() << endl;

return 1;
}

It's easy to understand that (2) works, because sum.operator()( int) is
called implicitly. (1) also works, it confuses me. Does Sum<int>()
create an implicit class Sum object? On the other hand, Sum<int>
doesn't work.
(3) fails, does it means the third argument of "for_each" couldn't be a
function pointer? What will the code be if I want to pass a function
pointer here? Thanks for help!

Jan 23 '07 #1
2 1702
On 22 Jan 2007 22:50:56 -0800, hn.ft.pris wrote:
>I've got following code test C++'s functor. For the sake of
easy-reading, I omit some declearations.

#include <algorithm>
#include <functional>

using namespace std;

template <typename Tclass Sum{
public:
Sum(T i=0):sum(i){};
inline void operator () (T x){
sum += x;
}
inline T output() const{
return sum;
}

private:
T sum;
};
This is a (probably) problematic 'stateful predicate', see:
http://www.gotw.ca/gotw/052.htm.
>int main( void ){
vector<intvec(1 0, 1);

Sum<intsum;

sum = for_each(vec.be gin(), vec.end(), Sum<int>()); .......(1)
sum = for_each(vec.be gin(), vec.end(), sum); .........(2)
sum = for_each(vec.be gin(), vec.end(), sum.operator()( int) ); ...(3)

cout << sum.output() << endl;

return 1;
}

It's easy to understand that (2) works, because sum.operator()( int) is
called implicitly. (1) also works, it confuses me. Does Sum<int>()
create an implicit class Sum object? On the other hand, Sum<int>
doesn't work.
(3) fails, does it means the third argument of "for_each" couldn't be a
function pointer? What will the code be if I want to pass a function
pointer here? Thanks for help!
The third argument in (3) is neither a function object nor a pointer
to a (free) function.

Best wishes,
Roland Pibinger
Jan 23 '07 #2

sum = for_each(vec.be gin(), vec.end(), sum.operator()( int) ); ...(3)
(3) fails, does it means the third argument of "for_each" couldn't be a
function pointer? What will the code be if I want to pass a function
pointer here? Thanks for help!
sum.operator()( int) isn't valid. You can't take an address of a member
function from an instance, you have to take it from the class. As such
its signature changes from what it was, (int) in this case, to
accepting a pointer to an instance of that class...so (Sum*, int) in
this case. To use such in an algorithm you need a binder. I use TR1
bind, which can be found as boost::bind.

sum = for_each(vec.be gin(), vec.end(), boost::bind(&Su m::operator(),
&sum, _1));

Jan 23 '07 #3

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

Similar topics

7
7211
by: What-a-Tool | last post by:
How does the expire date work setting it server side with asp. I know with javascript setting it client side it will be set to the clients local time, and therefore expire when the clients local time reaches the set expire-time. But if it is an expire time set on my server in California, and the cookie is put on a computer that is running on London Time, and the expire time is set at the server as 20 minutes from now, the London computer...
11
4751
by: ma740988 | last post by:
I'm perusing a slide with roughly 12 bullets spread across 3 pages. Each bullet reflects 'advice'. I'm ok with all but 1 bullet, more specifically the bullet that states: " Avoid the STL unless absolutely necessary " Now, I'm not acclimated with much C++ history, but something tells me this is akin to trepidation that surrounded C++ during it's inception? IOW, is this 'old school' rhetoric or ..... How do you refute this argument?
37
1524
by: Gregory Guthrie | last post by:
I am comparing Python to a few other scripting languages, and used a simple anagrams program as a sample. I was surprised ast a few python features that did not work as I would expect/wish; which caused less compact/expressive program styles that I wanted - reverting to a FORTRAN like series of assignments. For example, - why is len() not a member function of strings? Instead one says len(w).
27
2154
by: Chad | last post by:
The problem is: Write a recursive version of the function reverse(s), which reverses the string s in place. In "The C Answer Book", Second Edition, near the bottom of page 95, the authors say "This is not a good application of recursion". Just for the record, I did make an attempt at the solution before I broke down and looked at the solution in the book.
1
1555
by: petermichaux | last post by:
Hi, I have a general JavaScript library API design question based on some examples I have seen. There seem to be two options The first option is used by the AJAX libraries and by Matt Kruse's AJAX library. These seem like functional programming. YAHOO.util.connect.asyncRequest('GET', '/the/url', {success:function(o){alert(responseText)};});
3
303
by: hn.ft.pris | last post by:
I've got following code test C++'s functor. For the sake of easy-reading, I omit some declearations. #include <algorithm> #include <functional> using namespace std;
15
3796
by: nikki_herring | last post by:
I am using setTimeout( ) to continuously call a function that randomly rotates/displays 2 images on a page. The part I need help with is the second image should rotate 3 seconds after the first image rotates. I cannot figure out how to accomplish the 3 second delay. My code is pasted below: function randPic(){ randPic1(); randPic2();
18
1928
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
139
5980
by: Joe Mayo | last post by:
I think I become more and more alone... Everybody tells me that C++ is better, because once a project becomes very large, I should be happy that it has been written in C++ and not C. I'm the only guy thinking that C is a great programming language and that there is no need to program things object oriented. Many people says also that they save more time by programming projects object oriented, but I think its faster to program them in a...
19
1329
by: Frank Stutzman | last post by:
My apologies in advance, I'm new to python Say, I have a dictionary that looks like this: record={'BAT': '14.4', 'USD': '24', 'DIF': '45', 'OAT': '16', 'FF': '3.9', 'C3': '343', 'E4': '1157', 'C1': '339', 'E6': '1182', 'RPM': '996', 'C6': '311', 'C5': '300', 'C4': '349', 'CLD': '0', 'E5': '1148', 'C2': '329', 'MAP': '15', 'OIL': '167', 'HP': '19', 'E1': '1137', 'MARK': '', 'E3': '1163', 'TIME': '15:43:54',
0
9489
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
10072
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...
1
9885
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
8737
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
6562
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
5172
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
3829
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
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
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.