元编程总结

编译期算结果C98示例:

1
2
3
4
5
6
7
template <int n> struct fact98 {
 static const int value = n * fact98<n - 1>::value;
};
template <> struct fact98<0> {
 static const int value = 1;
};
std::cout << fact98<5>::value << std::endl;

或C11的示例:

1
2
3
constexpr int fact11(int n) {
 return n <= 1 ? 1 : (n * fact11(n - 1));
}

C11中不能使用变量和循环,C14中可以:

1
2
3
4
5
constexpr int fact14(int n) {
 int s = 1;
 for (int i = 1; i <= n; i++) { s = s * i; }
 return s;
}

编译期检查1:

1
2
3
4
5
6
7
static_assert(sizeof(void *) == 8, "expected 64-bit platform");
 
template<typename T, int Row, int Column>
struct Matrix {
 static_assert(Row >= 0, "Row number must be positive.");
 static_assert(Column >= 0, "Column number must be positive.");
};

编译期检查2:

1
2
3
4
5
6
7
8
9
struct A {
void foo(){}
 int member;
};
template<typename Function>
std::enable_if_t<!std::is_member_function_pointer_v<Function>> foo(Function&& f) {
}
foo([] {}); //ok
foo(&A::foo); //compile error: no matching function for call to 'foo(void (A::*)())'

编译期检查3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template< class, class = void >
struct has_foo : std::false_type {};
template< class T >
struct has_foo< T, std::void_t<decltype(std::declval<T>().foo())> > : std::true_type {};
template< class, class = void >
struct has_member : std::false_type {};
template< class T >
struct has_member< T, std::void_t<decltype(std::declval<T>().member)> > : std::true_type {};
struct A {
 void foo(){}
 int member;
};
static_assert(has_foo< A >::value);
static_assert(has_member< A >::value);

refer to: https://www.toutiao.com/a6646250452335723021/