473,728 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Various template approaches to avoid pointer to function penalty

This is from a thread that I posted on another forum some days ago.
I didn't get any response, so I'm proposing it in this ng in hope of
better luck :)

The standard explanation is that pointer to functions are hard to
inline for the compiler, and so you won't be able to avoid function
call overhead.
This is an important aspect when you are calling a function very
frequently for evaluation reason: think of the problem of performing
numerical integration of function double f(double x).
Another example is the qsort algorithm with different comparison
functions.
The various approaches that I found are:

1) If you are working with 1 function only:

A) Function object approach:
Suppose myfunc is a class with overloaded operator(), then we consider

template<class Fo>
double integrate(Fo f, int n) {
.....
sum += f(i/n);
.....
};
(I know you can use const Fo& f for better performances... .)

and call the integration routine with:
integrate(myfun c(),10);

First question: what is myfunc() ? An object of type myfunc? Why?
I would have used:

myfunc f;
integrate(f, 10);

The object has to be created (as an obj of type myfunc is passed to
the function).
If I understand correctly integrate(f, 10) = integrate<myfun c>(f, 10)
as the argument is deduced....

B) Pointer to function as template parameter approach:
Suppose myfunc is a function (take and returns double), then

template<double fp(double)>
double integrate(int n) {
.....
sum += fp(i/n);
.....
};

integrate<myfun c>(10);

I understand the function obj approach is more general: here I just
have the function, previously I had a object (that can embed data and
functions).
Question: In this situation myfunc is not passed to integrate (more
precisely no pointer to this function is passed...). It's like when we
use template parameters for classes. I expect a "substituti on" of fp
with the passed myfunc as the code is generated (like for template
classes).
Does this means that we have to distinguish between template arguments
objects that gets passed to the function and template arguments that
are "substitute d" word by word like in classes? (see below D)

2) Now to the case where I'm passing more functions (like a function
and the first derivative, they belongs to the same "object").

C) Class as template parameter approach:
Suppose myclass is a class with member functions f1 f2 (as usual take
and return)

template<class fclass>
double integrate(int n) {
.....
sum += fclass::f1(i/n) + fclass::f2(i/n);
.....
};

integrate<mycla ss>(10);

Here again is it working like situation B?
In B I had a template parameter of type pointer to function, while
here I have a template type parameter.
Maybe the point is that, even if no object here is created I'm able to
use static data inside the class, and define functions f1, f2 that
depends on this data? (while previously I had no class, just the
pointer to function so this possibility was precluded...)

D) A more general apporach:
Suppose myclass is a class with member funcions f1 f2 (as usual double
double)

template<class fclass, double (flcass::*fun1) (double),
double(fclass:: *fun2)(double)>
double integrate(int n, const fclass& fc) {
.....
sum += (fc.*fun1)(i/n) + (fc.*fun2)(i/n);
.....
};

myclass mc;
integrate<mycla ss, &myclass::f1 , &myclass::f2>(1 0, mc);

I understand this approach is more general: not only I choose the
class, but also I can choose the functions of the class that I'm using
in integrate.
Also I create the obj class, so I can have different objects of the
same class with different data member values (while previously only
static data could be used).
I understand his use of pointers to member functions.
So do we need to consider:
fc.*fun1
because I'm considering the particular obj mc of type myclass (and so,
even if the function of every obj of type myclass are the same, they
may depend on different data inside this obj) ?

Do you have any general comment on these approaches?
Thank you in advance for any help!
Best Regards
StephQ

Feb 26 '07 #1
5 2267
* StephQ:
>
Do you have any general comment on these approaches?
Measure before you try to optimize.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 26 '07 #2
StephQ a écrit :
This is from a thread that I posted on another forum some days ago.
I didn't get any response, so I'm proposing it in this ng in hope of
better luck :)

The standard explanation is that pointer to functions are hard to
inline for the compiler, and so you won't be able to avoid function
call overhead.
This is an important aspect when you are calling a function very
frequently for evaluation reason: think of the problem of performing
numerical integration of function double f(double x).
Another example is the qsort algorithm with different comparison
functions.
The various approaches that I found are:

1) If you are working with 1 function only:

A) Function object approach:
Suppose myfunc is a class with overloaded operator(), then we consider

template<class Fo>
double integrate(Fo f, int n) {
....
sum += f(i/n);
....
};
(I know you can use const Fo& f for better performances... .)

and call the integration routine with:
integrate(myfun c(),10);

First question: what is myfunc() ? An object of type myfunc? Why?
I would have used:

myfunc f;
integrate(f, 10);
Named object used to prevent optimization. Perhaps this is a legacy.
Personnaly, I prefer integrate(myfun c(),10); because then I remember the
object is passed by value.
>
The object has to be created (as an obj of type myfunc is passed to
the function).
If I understand correctly integrate(f, 10) = integrate<myfun c>(f, 10)
as the argument is deduced....

B) Pointer to function as template parameter approach:
Suppose myfunc is a function (take and returns double), then

template<double fp(double)>
double integrate(int n) {
....
sum += fp(i/n);
....
};

integrate<myfun c>(10);

I understand the function obj approach is more general: here I just
have the function, previously I had a object (that can embed data and
functions).
And in particular object can take a parameter. This approach needs a new
function for each metaparameter.
By example, if I want to compute different sum of powered:
- object case:
struct powfun{
const int p;
powfun(int powval):p(powva l){}
double operator(double x){return pow(x,p);
//...
};
And then
integrate(powfu n(2),10);
integrate(powfu n(3),10);
....
- function case
double pow2(double x){return pow(x,2);}
double pow3(double x){return pow(x,3);}
.....

Question: In this situation myfunc is not passed to integrate (more
precisely no pointer to this function is passed...). It's like when we
use template parameters for classes. I expect a "substituti on" of fp
with the passed myfunc as the code is generated (like for template
classes).
Does this means that we have to distinguish between template arguments
objects that gets passed to the function and template arguments that
are "substitute d" word by word like in classes? (see below D)
No but class can also carry traits which is not the case with function.
This is useful for object function composition.
>
2) Now to the case where I'm passing more functions (like a function
and the first derivative, they belongs to the same "object").

C) Class as template parameter approach:
Suppose myclass is a class with member functions f1 f2 (as usual take
and return)

template<class fclass>
double integrate(int n) {
....
sum += fclass::f1(i/n) + fclass::f2(i/n);
....
};

integrate<mycla ss>(10);

Here again is it working like situation B?
In B I had a template parameter of type pointer to function, while
here I have a template type parameter.
Maybe the point is that, even if no object here is created I'm able to
use static data inside the class, and define functions f1, f2 that
depends on this data? (while previously I had no class, just the
pointer to function so this possibility was precluded...)
You still cannot have metaparameters in a practical way.
>
D) A more general apporach:
Suppose myclass is a class with member funcions f1 f2 (as usual double
double)

template<class fclass, double (flcass::*fun1) (double),
double(fclass:: *fun2)(double)>
double integrate(int n, const fclass& fc) {
....
sum += (fc.*fun1)(i/n) + (fc.*fun2)(i/n);
....
};
The only reason you would want to pass a reference of fclass would be to
be able to use a derived class but the standard specifies function
object can be copied and then you have slicing.
Let say you pass it by value.
>
myclass mc;
integrate<mycla ss, &myclass::f1 , &myclass::f2>(1 0, mc);

I understand this approach is more general: not only I choose the
class, but also I can choose the functions of the class that I'm using
in integrate.
This approach doesn't add anything. If you need to compose a class
operation, the better is to do it in a function that can be called.
And if you think about implmenting all functions in a single class and
then be able to chose the member function to use, that is a design I
would avoid (I would even refactor a code to avoid it).
Also I create the obj class, so I can have different objects of the
same class with different data member values (while previously only
static data could be used).
I understand his use of pointers to member functions.
So do we need to consider:
fc.*fun1
because I'm considering the particular obj mc of type myclass (and so,
even if the function of every obj of type myclass are the same, they
may depend on different data inside this obj) ?
Feb 27 '07 #3
Measure before you try to optimize.
Yes, profiling the code is always a good practice.
This was just a thread to check if my understanding of the subject was
at least acceptable :P

StephQ
>
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Feb 28 '07 #4
and call the integration routine with:
integrate(myfun c(),10);
First question: what is myfunc() ? An object of type myfunc? Why?
I would have used:
myfunc f;
integrate(f, 10);

Named object used to prevent optimization. Perhaps this is a legacy.
Personnaly, I prefer integrate(myfun c(),10); because then I remember the
object is passed by value.
So myfunc() just calls the default constructor and the created obj is
passed to integrate.
I don' t understand why you say that from the syntax you remember that
the object is passed by value.
I could have defined the template function integrate this way too to
use pass by reference:

template<class Fo>
double integrate(const Fo& f, int n) { //instead of (Fo f, int n)
....
sum += f(i/n);
....
};

integrate(myfun c(),10);

...class can also carry traits which is not the case with function.
This is useful for object function composition.
For object function composition you mean when, for example, you call
the sort algorithm and use different comparison criteria right?

D) A more general apporach:
Suppose myclass is a class with member funcions f1 f2 (as usual double
double)
template<class fclass, double (flcass::*fun1) (double),
double(fclass:: *fun2)(double)>
double integrate(int n, const fclass& fc) {
....
sum += (fc.*fun1)(i/n) + (fc.*fun2)(i/n);
....
};

The only reason you would want to pass a reference of fclass would be to
be able to use a derived class but the standard specifies function
object can be copied and then you have slicing.
Let say you pass it by value.
I use pass by reference because I want to avoid copying the object, as
the copy operation could be time expensive if the object is big.
Is there good reasons to use pass by value instead? (I don't have
conversion problems....)
How would you have defined integrate in this situation?
>

myclass mc;
integrate<mycla ss, &myclass::f1 , &myclass::f2>(1 0, mc);
I understand this approach is more general: not only I choose the
class, but also I can choose the functions of the class that I'm using
in integrate.

This approach doesn't add anything. If you need to compose a class
operation, the better is to do it in a function that can be called.
And if you think about implmenting all functions in a single class and
then be able to chose the member function to use, that is a design I
would avoid (I would even refactor a code to avoid it).
I don't understand what you mean here.
Suppose we write an algorithm for finding the maximum of a function
that uses the function and the first derivative of the function.
We can define a class containing the function parameters as private
data, and the function and the first derivative of the function as
public member functions of the class.
We can then call the alg for any of these classes.
We let the user select the name of f and f' in the classes because
probably these names have particular meanings depending on the
"object" that these classes represents.
Is there a better way to accomplish this task?

Thank you for your reply.
StephQ
Feb 28 '07 #5
StephQ a écrit :
>>and call the integration routine with:
integrate(myf unc(),10);
First question: what is myfunc() ? An object of type myfunc? Why?
I would have used:
myfunc f;
integrate(f , 10);
Named object used to prevent optimization. Perhaps this is a legacy.
Personnaly, I prefer integrate(myfun c(),10); because then I remember the
object is passed by value.

So myfunc() just calls the default constructor and the created obj is
passed to integrate.
I don' t understand why you say that from the syntax you remember that
the object is passed by value.
I could have defined the template function integrate this way too to
use pass by reference:

template<class Fo>
double integrate(const Fo& f, int n) { //instead of (Fo f, int n)
....
sum += f(i/n);
....
};

integrate(myfun c(),10);
It is STL deformation I presume.

>
>...class can also carry traits which is not the case with function.
This is useful for object function composition.

For object function composition you mean when, for example, you call
the sort algorithm and use different comparison criteria right?
I mean composing binary function object with not2(), compose2(), plus(), ...

>
>>D) A more general apporach:
Suppose myclass is a class with member funcions f1 f2 (as usual double
double)
template<clas s fclass, double (flcass::*fun1) (double),
double(fclass ::*fun2)(double )>
double integrate(int n, const fclass& fc) {
....
sum += (fc.*fun1)(i/n) + (fc.*fun2)(i/n);
....
};
The only reason you would want to pass a reference of fclass would be to
be able to use a derived class but the standard specifies function
object can be copied and then you have slicing.
Let say you pass it by value.

I use pass by reference because I want to avoid copying the object, as
the copy operation could be time expensive if the object is big.
Is there good reasons to use pass by value instead? (I don't have
conversion problems....)
How would you have defined integrate in this situation?
Yes, here it is possible. Again STL polution.

But then, I would have used accumulate() template with a functor parameter.

template<typena me T>
struct add_mean : public binary_function <T,T,T>
{
const size_t n;
add_mean(size_t number):n(numbe r){}
T operator() (const T& sum, const T& x) const{return sum+x/n;}
};

accumulate (v.begin(),v.en d(),0.0,add_mea n<double>(v.siz e()));
>
>>
>>myclass mc;
integrate<myc lass, &myclass::f1 , &myclass::f2>(1 0, mc);
I understand this approach is more general: not only I choose the
class, but also I can choose the functions of the class that I'm using
in integrate.
This approach doesn't add anything. If you need to compose a class
operation, the better is to do it in a function that can be called.
And if you think about implmenting all functions in a single class and
then be able to chose the member function to use, that is a design I
would avoid (I would even refactor a code to avoid it).

I don't understand what you mean here.
Suppose we write an algorithm for finding the maximum of a function
that uses the function and the first derivative of the function.
We can define a class containing the function parameters as private
data, and the function and the first derivative of the function as
public member functions of the class.
We can then call the alg for any of these classes.
We let the user select the name of f and f' in the classes because
probably these names have particular meanings depending on the
"object" that these classes represents.
Is there a better way to accomplish this task?
It is a way to it but not in the case you mentioned in the OP where the
accumulating function was:
sum += (fc.*fun1)(i/n) + (fc.*fun2)(i/n);
in this case, it is likely to be more efficient (I would have to test to
be sure) and more maintainable to define a functor that return double
operator(double sum, double i){return sum+fc.fun1(i/n)+fc.fun2(i/n)}.

However, I find it strange to define a template taking adapation to the
member function to call; it is not a clear design in THIS case.
I would rather require an adaptor
template<typena me ARG, typename RET>
struct derivable_funct ion
{
//traits
RET function(const ARG& x);
RET derivative(cons t ARG& x);
};

An then, for each case:
struct myclass_derivat ion: public derivable_funct ion<double,doub le>
{
const myclass& fun;
myfunc(const myclass& obj):fun(obj){}
double function(const double& x){return fun.f1(x);}
double derivative(cons t double& x){return fun.f2(x);}
}

Michael
Feb 28 '07 #6

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

Similar topics

5
4463
by: Marc Schellens | last post by:
I have: char* byteN = "BYTE"; char* byte_fun() { return type_fun< byteN>(); } char* fix_fun() {
12
4585
by: Surya Kiran | last post by:
Hi all, I've written a function template. say template <class T> fn (T var) { ... } Is there any way, from within the function, can we check what type of argument we've passed on to the function (double, float etc) ?? Thanks in advance,
4
4803
by: Eric | last post by:
Does anyone know if you can specialize a template function for arguments that are pointers to a particular base class and not lose the subclass type? example: template <class E> void DeliverEvent(E *Event); is a function that will receive an Event object, and then eventually
2
2175
by: Chris Schadl | last post by:
Hi, I'm working on writing a templated Binary Search Tree class in C++. In regular C, I would have functions which traverse the tree take a pointer to a user-defined function as an argument, which would then execute the user-defined function for each node that is "visited". For example: /* in the BST header file */ /* I actually don't remember if this is valid C or not */ typedef void (*fn)(void* tree_item);
8
11365
by: vpadial | last post by:
Hello, I want to build a library to help exporting c++ functions to a scripting languagge. The scripting language provides a function to register functions like: ANY f0() ANY f1(ANY) ANY f2(ANY, ANY) ANY f3(ANY, ANY, ANY)
4
2251
by: firegun9 | last post by:
Hello everyone, here is my program: /////////////////////////////// #include <iostream> using namespace std; void multi(double* arrayPtr, int len){ for(int i=0; i<len; i++) *(arrayPtr+i)*=2;
6
4004
by: RainBow | last post by:
Greetings!! I introduced the so-called "thin-template" pattern for controlling the code bloat caused due to template usage. However, one of the functions in the template happens to be virtual as well. To support thin-template, I need to make virtual function as inline. Now, I know that compiler would generate an out-of-line copy when it
45
2904
by: charles.lobo | last post by:
Hi, I have recently begun using templates in C++ and have found it to be quite useful. However, hearing stories of code bloat and assorted problems I decided to write a couple of small programs to check. What I expected was that there would be minor code bloat and some speed improvement when using templates. However... I wrote a basic list container (using templates), and a list container (using virtual derived classes). I also tried...
9
2038
by: jedi200581 | last post by:
Hello, I have a singleton class that I'm using through macros: //snippet #define DO_SOMETHING ( myArgument) \ { \ MyClass *myObject = MyClass::getInstance(); \ myObject->doSomething(myArgument); \ }; \
0
8905
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
8759
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
9278
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
9199
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
4524
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
4794
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3236
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
2671
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2161
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.