模板元编程
现代模板元编程 - 第一部分 - Cppcon 2014 - Walter E. Brown
| Text Only |
|---|
| #include<stdio.h>
// example 1
template<unsigned M, unsigned N>
struct gcd
{
static int const value = gcd<N, M % N>::value;
};
template<unsigned M>
struct gcd<M, 0>
{
static_assert(M != 0);
static int const value = M;
};
// example 2
template<class T>
struct rank
{
static size_t const value = 0u;
};
template<class U, size_t N>
struct rank<U[N]>
{
static size_t const value = 1u + rank<U>::value;
};
// example 3
template<class T>
struct remove_const
{
using type = T;
};
template<class U>
struct remove_const<U const>
{
using type = U;
};
// example 4
template<class T>
struct type_is
{
using type = T;
};
template<class T>
struct remove_volatile : type_is<T> {};
template<class U>
struct remove_volatile<U volatile> : type_is<U> {};
// example 5
// primary template
template<bool, class T,class>
struct IF : type_is<T> {};
// spetialization
template<class T, class F>
struct IF<false, T, F> : type_is<F> {};
int main(){
printf("%d\n", gcd<666,324>::value);
using array_t = int[10][20][30];
printf("%ld\n", rank<array_t>::value);
remove_const<int const>::type t;
// remove_const_t<int const> t; // in c++14
}
|