This is what I want to accomplish (pseudo code)
parameter <op>
func()
{
for i loop
for j loop
for k loop
x[G(i,j,k)] = x[H(i,j,k)] <op> y[I(i,j,k)]
end loop
end loop
end loop
}
main()
{
func<+>() or func<'+'>()
func<->() or func<'-'>()
}
Do let me know if its possible to do this in C++. I know templates,
but I think they cannot be used for this.
Regards
Varun
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
[snip]
>
> Do let me know if its possible to do this in C++. I know templates,
> but I think they cannot be used for this.
They can be. You need std::plus and std::minus from <functional>
header.
#include <functional>
some_type x[], y[];
template <class op_type>
func(const op_type& op)
{
for i loop
for j loop
for k loop
x[G(i,j,k)] = op(x[H(i,j,k)], y[I(i,j,k)]);
end loop
end loop
end loop
}
int main()
{
func(std::plus<some_type>());
func(std::minus<some_type>());
}
you can also specify operator type inside func if you need:
template <template <class> class op_type>
func()
{
op_type<some_type> op;
...
x[G(i,j,k)] = op(x[H(i,j,k)], y[I(i,j,k)]);
...
}
func<std::plus>();
--
Konstantin.
You can do this, but not with that syntax. The <functional> header
includes "plus", "minus", etc. that may be used for this purpose.
Basically, you should give your function a template parameter named
BINARY_OPERATOR, and you can apply it using:
BINARY_OPERATOR op;
result = op(left_operand,right_operand);
When you instantiate the template, simply use std::plus, std::minus,
std::multiplies, std::divides, or std::modulus as the template
parameter. If you need more complicated binary operations, you can
create your own binary operator structure, as long as it has the same
generic interface.
http://www.sgi.com/tech/stl/plus.html
On Nov 12, 8:18 pm, banu <varun.nagp...@gmail.com> wrote:
> I am trying to do something, which I think is not possible to do in C+
> +.
>
> This is what I want to accomplish (pseudo code)
>
> parameter <op>
> func()
> {
> for i loop
> for j loop
> for k loop
> x[G(i,j,k)] = x[H(i,j,k)] <op> y[I(i,j,k)]
> end loop
> end loop
> end loop
>
[snipped]
>
> Do let me know if its possible to do this in C++. I know templates,
> but I think they cannot be used for this.
>
> Regards
> Varun
>
> --
> [ Seehttp://www.gotw.ca/resources/clcm.htmfor info about ]
Yes, templates can be used for this - here's a simplified version of
what (I think) you want:
int add( int a, int b ) {
return a + b;
}
int sub( int a, int b ) {
return a - b;
}
template <typename FP>
int ApplyFP ( FP func ) {
int sum = 0;
for ( int i = 0; i < 10; i++ ) {
sum += func( i, 42 );
}
return sum;
}
int main() {
int a= 1, b = 2;
int c = ApplyFP( add );
int d = ApplyFP( sub );
}
Neil Butterworth