Skip to content

Instantly share code, notes, and snippets.

@zah
Created July 15, 2012 15:42
Show Gist options
  • Select an option

  • Save zah/3117494 to your computer and use it in GitHub Desktop.

Select an option

Save zah/3117494 to your computer and use it in GitHub Desktop.
#include <cstring>
#include <iostream>
class Base
{
struct SetParamHelper
{
Base* obj;
SetParamHelper(Base* obj): obj(obj) {}
const SetParamHelper& operator() (const char* name, int value) const
{
obj->setParam(name, value);
return *this;
}
};
public:
SetParamHelper setParams(const char* name, int value)
{
setParam(name, value);
return SetParamHelper(this);
}
virtual void setParam(const char* name, int value)
{
//
}
virtual int getParam(const char* name)
{
return -1;
}
};
#define SET_PARAM_FIRST(param) \
if(strcmp(name, #param) == 0) param = value;
#define SET_PARAM_NEXT(param) \
else if(strcmp(name, #param) == 0) param = value;
#define IMPLEMENT_SET_PARAM(PARAM_MAP) \
virtual void setParam(const char* name, int value) { PARAM_MAP(SET_PARAM_FIRST, SET_PARAM_NEXT); }
#define GET_PARAM_FIRST(param) \
if(strcmp(name, #param) == 0) return param;
#define GET_PARAM_NEXT(param) \
else if(strcmp(name, #param) == 0) return param;
#define IMPLEMENT_GET_PARAM(PARAM_MAP) \
virtual int getParam(const char* name, int value) { PARAM_MAP(GET_PARAM_FIRST, GET_PARAM_NEXT) else return -1; }
#define IMPLEMENT_GET_SET(PARAM_MAP) \
IMPLEMENT_SET_PARAM(PARAM_MAP) \
IMPLEMENT_GET_PARAM(PARAM_MAP)
#define DECLARE_PARAM(name) \
int name;
#define IMPLEMENT_PARAMS(PARAM_MAP) \
IMPLEMENT_GET_SET(PARAM_MAP) \
PARAM_MAP(DECLARE_PARAM, DECLARE_PARAM)
class Foo : public Base
{
public:
#define FOO_PARAMS(FIRST, NEXT) \
FIRST(intelligence) \
NEXT(wisdom) \
NEXT(charisma)
IMPLEMENT_PARAMS(FOO_PARAMS)
};
int main()
{
Foo f;
f.setParams
("wisdom", 10)
("intelligence", 25)
("charisma", 55);
std::cout << f.charisma;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment