Advertisement
triclops200

Smartfunc

Feb 1st, 2012
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #ifndef __SMARTFUNC_HPP__
  2. #define __SMARTFUNC_HPP__
  3. #include <stdarg.h>
  4. #include <map>
  5. #include <cstdio>
  6. #include <string>
  7. #include <sstream>
  8. namespace bstd{
  9.     template<class T, typename ... Args> class smartfunc{
  10.         public:
  11.             T (*funcpt)(smartfunc*, Args...args);
  12.             template<typename argT,typename...ArgsT>
  13.             std::string compile(std::string str,argT arg,ArgsT...args){
  14.                 std::ostringstream s;
  15.                 s << arg;
  16.                 str += ","+s.str();
  17.                 return compile(str, args...);
  18.             }
  19.             std::string compile(std::string str){
  20.                 return str;
  21.             }
  22.             std::map<std::string,T> m;
  23.             T call(Args... args){
  24.                 std::string arg = compile("",args...);
  25.                 if(m.find(arg) == m.end()){
  26.                     m[arg] = (*funcpt)(this,args...);
  27.                 }
  28.                 return m[arg];
  29.             }
  30.             T operator () (Args...args){
  31.                 return call(args...);
  32.             }
  33.             smartfunc(T (*functionPointer)(smartfunc*,Args...args)){
  34.                 funcpt = functionPointer;
  35.             }
  36.     };
  37. }
  38. /*
  39. EXAMPLE USAGE
  40. long long int fib(smartfunc<long long int,int>*f,int n){
  41.     if(n<2)
  42.         return n;
  43.     return (*f)(n-1) + (*f)(n-2);
  44. }
  45. int main(){
  46.     smartfunc<long long int, int> ffib(fib);
  47.     printf("%d\n",ffib(5));
  48.     printf("%d\n",ffib(100));
  49. }
  50. */
  51. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement