473,466 Members | 1,381 Online
Bytes | Software Development & Data Engineering Community
Create 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(myfunc(),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<myfunc>(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<myfunc>(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 "substitution" 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 "substituted" 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<myclass>(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<myclass, &myclass::f1, &myclass::f2>(10, 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 2241
* 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(myfunc(),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(myfunc(),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<myfunc>(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<myfunc>(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(powval){}
double operator(double x){return pow(x,p);
//...
};
And then
integrate(powfun(2),10);
integrate(powfun(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 "substitution" 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 "substituted" 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<myclass>(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<myclass, &myclass::f1, &myclass::f2>(10, 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(myfunc(),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(myfunc(),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(myfunc(),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<myclass, &myclass::f1, &myclass::f2>(10, 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(myfunc(),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(myfunc(),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(myfunc(),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<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?
Yes, here it is possible. Again STL polution.

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

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

accumulate (v.begin(),v.end(),0.0,add_mean<double>(v.size())) ;
>
>>
>>myclass mc;
integrate<myclass, &myclass::f1, &myclass::f2>(10, 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<typename ARG, typename RET>
struct derivable_function
{
//traits
RET function(const ARG& x);
RET derivative(const ARG& x);
};

An then, for each case:
struct myclass_derivation: public derivable_function<double,double>
{
const myclass& fun;
myfunc(const myclass& obj):fun(obj){}
double function(const double& x){return fun.f1(x);}
double derivative(const 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
by: Marc Schellens | last post by:
I have: char* byteN = "BYTE"; char* byte_fun() { return type_fun< byteN>(); } char* fix_fun() {
12
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...
4
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...
2
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,...
8
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...
4
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++)...
6
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...
45
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...
9
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(); \...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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,...
0
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...
0
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 ...

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.