C++ template metaprogramming introduction

Posted on Updated on

C++ template metaprogramming introduction.

So far I’m on chapter 3, and my source now looks like below:

#include <iostream>

template <int N, int D> struct Frak {
	static const long Num = N;
	static const long Den = D;
};

template <int N, typename F> struct ScalarMultiplication {
	typedef Frak<N*F::Num, F::Den> result;	
};

int main() {
	// std::cout << Factorial<5>::result << "\n";
	typedef Frak<2, 3> Two_Thirds;

	typedef ScalarMultiplication<2, Two_Thirds>::result Four_Thirds;
	std::cout << Four_Thirds::Num << "/" << Four_Thirds::Den << "\n";
	return 0;
}

When executed:

@benjamin.lo% g++ templates.cpp
@benjamin.lo% ./a.out
4/3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s