[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

Pass code as template parameter

Edward Jensen

11/6/2008 9:38:00 PM

Hi,

I need to write many instances like the following struct

struct Function191 : public Function {
double operator()(double x) {
return cos(x) - x;
}
friend std::ostream& operator<< (std::ostream& os, const Function191&
f) {
return os << "cos(x) - x";
}
};

Is there a way to generalize this, such that I can write a generic struct,
which takes a parameter which is both interpreted as code for
operator() and as string for operator<<? I was hoping it would be possible
with templates for example:
Func<"cos(x) - x"> f1;
Func<"exp(x) - log(x)"> f2;

Is this possible?

Best,
Edward


2 Answers

acehreli

11/6/2008 10:24:00 PM

0

On Nov 6, 1:37 pm, "Edward Jensen" <edw...@jensen.invalid> wrote:
> Hi,
>
> I need to write many instances like the following struct
>
> struct Function191 : public Function {
>      double operator()(double x) {
>          return cos(x) - x;
>      }
>      friend std::ostream& operator<< (std::ostream& os, const Function191&
> f) {
>          return os << "cos(x) - x";
>      }
>
> };
>
> Is there a way to generalize this, such that I can write a generic struct,
> which takes a parameter which is both interpreted as code for
> operator() and as string for operator<<? I was hoping it would be possible
> with templates for example:
> Func<"cos(x) - x"> f1;
> Func<"exp(x) - log(x)"> f2;

The preprocessor has two features:

- ## characters concatenate
- # character stringifies

First: macros are known to be messy.

Here is an example

#include <iostream>

struct Function
{};

#define DEFINE_FUNCTION(N,
code) struct Function##N : public Function
{ double operator()(double x)
{ return
(code); }
friend std::ostream& operator<< (std::ostream& os, const
Function##N&) { return os <<
#code; }
}

DEFINE_FUNCTION(191, x + 1);
DEFINE_FUNCTION(192, x / 2);

int main()
{
Function191 f191;
f191(5);
std::cout << f191 <<'\n';

Function192 f192;
f192(6);
std::cout << f192 << '\n';
}

Ali

Paavo Helde

11/6/2008 10:34:00 PM

0

"Edward Jensen" <edward@jensen.invalid> kirjutas:

>
> Is there a way to generalize this, such that I can write a generic
> struct, which takes a parameter which is both interpreted as code for
> operator() and as string for operator<<?

This seems like a task for a preprocessor macro. Introspective support in
C++ is almost non-existant, so one cannot do this kind of things in the
language itself.

hth
Paavo