Created
December 20, 2017 14:45
-
-
Save bit-hack/6ce9fd2be5b4a36ed09229241a8ed9ec to your computer and use it in GitHub Desktop.
de-virtual
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
struct base_t { | |
const int type; | |
base_t() : type(0) {} | |
base_t(int type) : type(type) {} | |
virtual int call() { return 1; } | |
}; | |
struct derived_t : public base_t { | |
derived_t() : base_t(1) {} | |
virtual int call() { return 2; } | |
}; | |
base_t *one_or_other() { | |
return (rand()&1) ? new base_t: (base_t*)new derived_t; | |
} | |
template <typename type_t> | |
int myloop(base_t *x, int itters) { | |
int accum = 0; | |
auto func = &type_t::call; | |
auto X = static_cast<type_t*>(x); | |
for (int i=0; i<itters; ++i) | |
accum += (X->*func)(); | |
return accum; | |
}; | |
int main(int argc, char**args) { | |
base_t *x = one_or_other(); | |
if (x->type == 0) | |
return myloop<base_t>(x, argc); | |
else if (x->type == 1) | |
return myloop<derived_t>(x, argc); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment