Created
April 6, 2015 23:39
-
-
Save c0ldlimit/dc34c9ca70c71aee3d52 to your computer and use it in GitHub Desktop.
#advcpp #hw1
This file contains 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<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; | |
} | |
} |
This file contains 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
// 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; | |
}; |
This file contains 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 <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