Creating Code Using Macros

I have a bunch of classes like:


class SomeClass : public Function{
public:

   ref call(ref args){
    // do & return stuff
   }

   int getType(){return TYPE;}
   ref toString(){ return "SomeClass";}
};

I got 50 of them, and the only thing that is different is the call function body. Is it possible to have a macro that will take the name and body and replace "SomeClass" with the name and insert the body into the call function?

+3
source share
3 answers

Of course. Extending the body of a member function is a callbit simpler if you have a compiler that supports variable macros. Although I used Boost.Preprocessor stringize macro, it is trivial to write your own.

#define DEFINE_CLASS(name, parenthesized_call_body)                 \
    class name : public Function {                                  \
        ref call (ref args) {                                       \
            DEFINE_CLASS_CALL_BODY parenthesized_call_body          \
        }                                                           \
        int getType() { return TYPE; }                              \
        const char* toString() { return BOOST_PP_STRINGIZE(name); } \
    };

#define DEFINE_CLASS_CALL_BODY(...) __VA_ARGS__

Used as:

DEFINE_CLASS(SomeClass, (return ref()))

call , , , . , call .

+4

, , , :

#define DEFINE_FUNCTION_CLASS_BEGIN(name) \
    class name : public Function { \
    public: \
        ref call(ref args) {

#define DEFINE_FUNCTION_CLASS_END \
        } \
        int getType() { return TYPE; } \
        void toString() { return #name; } \
    };

:

DEFINE_FUNCTION_CLASS_BEGIN(SomeClass)

// Stuff.

DEFINE_FUNCTION_CLASS_END

:

template<int Type>
class SomeClass : public Function {
public:
    int getType() { return Type; }
    ref call(ref args) {}
    std::string toString() {}
};

:

template<>
ref SomeClass<TYPE>::call(ref args) {
    // Stuff.
};

template<>
std::string SomeClass<FOO>::toString() {
    return "FOO";
};
+2

getType() toString()? Java #, , , , ++. , "SomeClass" , void.

, , .

template<typename T> class SomeClass : public Function {
    T t;
public:
    SomeClass(const T& ref)
        : t(ref) {}
    ret call(args) {
        return t(args);
    }
    int getType() { return TYPE; }
    std::string toString() { return "someClass"; } 
};

ret func(argtypes) { ... }
SomeClass<ret(*)(argtypes)> instance(func);
struct lols {
    // .. Whatever you want in here
    ret operator()(args) { ... };
}
SomeClass<lols> anotherinstance(lols()); // or constructor arguments if needed 
0

All Articles