Skip to content

Instantly share code, notes, and snippets.

@c0ldlimit
Created April 6, 2015 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c0ldlimit/dc34c9ca70c71aee3d52 to your computer and use it in GitHub Desktop.
Save c0ldlimit/dc34c9ca70c71aee3d52 to your computer and use it in GitHub Desktop.
#advcpp #hw1
#include<iostream>
// primary template
template<int i>
struct Fib {
static int const value = Fib<i-1>::value + Fib<i-2>::value;
};
// specializations to stop recursion
// specialization is indicated
template<>
struct Fib<0> {
static int const value = 0;
};
template<>
struct Fib<1> {
static int const value = 1;
};
using namespace std;
int main()
{
cut << Fib<8>::value << endl;
return 0;
}
}
// primary template
template<typename T, typename A, typename B> struct Replace;
// in this case there is general definition that makes sense
// so just leave it undefined
// Case: empty tuple (this is what needed to be added)
template<typename A, typename B>
struct Replace<tuple<>, A, B> {
typedef tuple<> Result;
}
// Case: type not found
template<typename H, typename...Ts, typename A, typename B>
struct Replace<tuple<H, Ts...>, A, B> : public Append<tuple<H>, typename Replace<tuple<Ts...>, A, B>::Result> {
};
// Case: type found!
template<typename... Ts, typename A, typename B>
struct Replace<tuple<A, Ts...>, A, B> {
typedef tuple <B, Ts...> Result;
};
#include <iostream>
void myPrintf(string format) { cout << format; }
template<typename H, typename ...Ts>
void myPrintf(string format, H const &h, Ts const &...ts) {
auto percent = format.find_first_of("%");
if(percent == string::npos)
thorw invalid_argument("Too many argument to printf");
cout << format.substr(0, percent);
cout << h;
myPrintf(format.substr(percent + 1), ts...);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment