C++ preprocessor concatenation -
i have function build function pointers. think might faster try exchange function pre processor macro. @ least, try out macro can measure if generates faster code.
it's more or less this:
typedef int (item::*getterptr)(void)const; typedef void (item::*setterptr)(int); void dostuff(item* item, getterptr getter, setterptr setter, int k) { int value = (item->*getter)(); // .. stuff (item->*setter)(newvalue); }
and it's called like
// ... dostuff(&item, &item::a, &item::seta, _a); dostuff(&item, &item::b, &item::setb, _b); dostuff(&item, &item::c, &item::setc, _c); // ...
i think might possible swap like:
#define do_stuff(item, getter, setter, k) { \ int value = item ## -> ## getter ## (); \ //... \ item ## -> ## setter ## (newvalue); \ } while(0);
but gives me errors like:
error: pasting ")" , "seta" not give valid preprocessing token
there's way concatenate function names , it's object?
token-pasting means "combining 2 tokens form single token".
you don't want that. ptr_to_item->a()
isn't 1 token. assuming ptr_to_item
variable name, it's 5: ptr_to_item
, ->
, a
, (
, )
.
your macro should be:
#define do_stuff(item, getter, setter, k) { \ int value = (item)->getter(); \ //... \ (item)->setter(newvalue); \ } while(0);
by way, macro haters, avoids macros while avoiding use of pointer-to-member-function function parameter. tried if macro faster questioner's function due call through pointer not being inlined. don't know if/when make difference:
#include <iostream> struct { int f; int foo() {return f;} void setfoo(int a) { f = a; } }; template <typename t, typename u, u (t::*getter)(), void (t::*setter)(u)> void doit(t &obj, u k) { u value = (obj.*getter)(); value += k; (obj.*setter)(value); } int main() { a = {0}; std::cout << a.foo() << "\n"; doit<a,int,&a::foo, &a::setfoo>(a,1); std::cout << a.foo() << "\n"; doit<a,int,&a::foo, &a::setfoo>(a,2); std::cout << a.foo() << "\n"; }
because it's there.
there's @ least 1 weakness. u can't reference type in template. since it's fixed int
in code in question, template parameter u may not needed @ all, isn't limiting.
Comments
Post a Comment