C Board  

Go Back   C Board > General Programming Boards > C++ Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 11-21-2007, 06:19 PM   #1
Registered User
 
Join Date: Apr 2007
Posts: 282
Is this claim correct: "Anywhere you pass in a function, you can pass in a functor"?

Is this claim correct: "Anywhere you pass in a function, you can pass in a functor"?

for example:
Code:
bool cmp_function(int a, int b){
return a<b;
}

struct cmp_functor{
bool operator()(int a, int b){
return a<b;
}
};

std::sort(vec.begin(), vec.end(), cmp_function);
std::sort(vec.begin(), vec.end(), cmp_functor);
meili100 is offline   Reply With Quote
Old 11-21-2007, 06:48 PM   #2
Guest
 
Sebastiani's Avatar
 
Join Date: Aug 2001
Posts: 5,034
no, that is incorrect. but you can often structure your code in a way that allows either to be used. for example:

Code:
template <typename Function>
void
foo(Function callback, int data)
{
	callback(data);
}

void
bar(int)
{	}

struct baz
{
	void
	operator () (int)
	{	}
};

foo(bar, 1);
foo(baz(), 1);
Sebastiani is offline   Reply With Quote
Old 11-21-2007, 07:15 PM   #3
Registered User
 
Join Date: Apr 2007
Posts: 282
Thank you, I am curious why "baz()" should carry "()". Isn't "baz" enough?

Also, in your example, what would the 2 signatures be if the foo only accepts function or funcotr?

Last edited by meili100; 11-21-2007 at 07:21 PM.
meili100 is offline   Reply With Quote
Old 11-22-2007, 12:58 AM   #4
MENTAL DETECTOR
 
whiteflags's Avatar
 
Join Date: Apr 2006
Location: United States
Posts: 3,295
> I am curious why "baz()" should carry "()". Isn't "baz" enough?
Because baz is an object that needs to be instantiated, just like other classes or structs in C++.

> what would the 2 signatures be if the foo only accepts function or funcotr?
The simplest of the possibilities is probably

void foo( void (*callback )( int ), int data );
void foo( baz callback, int data );
whiteflags is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Compiling sample DarkGDK Program Phyxashun Game Programming 6 01-27-2009 03:07 AM
dllimport function not allowed steve1_rm C++ Programming 5 03-11-2008 03:33 AM
We Got _DEBUG Errors Tonto Windows Programming 5 12-22-2006 05:45 PM
How to fix misaligned assignment statements in the source code? biggyK C++ Programming 28 07-16-2006 11:35 PM
qt help Unregistered Linux Programming 1 04-20-2002 09:51 AM


All times are GMT -6. The time now is 02:10 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22