template calculates 4 + 3 + 2 + 1


This is a “hello world” for template metaprogramming.
MetaFunc() return 10 because (4 + 3 + 2 + 1) equals 10.

template<int n>
int MetaFunc()
{
	return n +  MetaFunc<n-1>();
}
template<>
int MetaFunc<1>()
{
	return 1;
}
int TestMetaFunc()
{
	return MetaFunc<4>(); //4 + 3 + 2 + 1 == 10
}
Advertisements

Minimum template allocator


A minimum template allocator tested on std::vector and std::sort.

It’s just to show how allocators work.
The code is kept to minimum so that the key points can be easily seen.

#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;

template <class T> class Alloc;
template <> struct Alloc<void>
{ typedef const void* const_pointer;
};
template <class T>
class Alloc
{
public:
 typedef size_t size_type;
 typedef ptrdiff_t difference_type;
 typedef T*pointer;
 typedef const T*const_pointer;
 typedef T& reference;
 typedef const T& const_reference;
 typedef T value_type;
 template <class U>
 struct rebind
 { typedef Alloc<U> other;
 };
 Alloc() {}
 template <class U>
 Alloc(const Alloc<U>&) {}
 pointer allocate(size_type num)
 {
  return pointer(malloc(num * sizeof T));
 }
 void deallocate(pointer p, size_type n)
 {
  free(p);
 }
 size_type max_size() const
 {
  return 4;
 }
 void construct(pointer p, const T& val)
 {
  new((void*)p)T(val);
 }
 void destroy(pointer p)
 {
  p->~T();
 }
};
void TestAlloc()
{
 vector<int, Alloc<int>> v;
 v.push_back(2);
 v.push_back(1);
 sort(v.begin(), v.end());
 assert(v[0] == 1);
 assert(v[1] == 2);
}

What if always use class for typename?


Anything wrong with this template class?

template <typename T>
class C
{
 typedef class T::SubType Subtype2;
};

It compiles fine on VS2011 without extenstion. This makes me wonder if keyword ‘typename’ can be removed from MSVB leaving only ‘class’ there.
Please let me know when typename HAS to be used.