acehreli
11/6/2008 10:24:00 PM
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