Pass code as template parameter

E

Edward Jensen

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::eek:stream& operator<< (std::eek:stream& 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
 
A

acehreli

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::eek:stream& operator<< (std::eek:stream& 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::eek:stream& operator<< (std::eek:stream& 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
DewittMill
Top