constexpr
constexpr 函数是在使用需要它的代码时,可以在编译时计算其返回值的函数。当其参数为 constexpr 值并且在编译时使用代码需要返回值时(例如,初始化一个 constexpr 变量或提供一个非类型模板参数),它会生成编译时常量。
enable_if 的使用
enable_if<true, T>::type 即为 T,而 enable_if<false, T>::type 会引发编译错误
大多数时候 enable_if 都用来判断模板参数的类型,此时一般要和 is_integral 等模板类结合使用。
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T, typename = typename enable_if<is_integral<T>::value, void>::type>
bool isodd(T x)
{
return x % 2;
}
int main()
{
cout << isodd(4) << endl << isodd('a');
//cout << isodd("qwq"); -- compile error
return 0;
}
std::is_base_of
is_base_of 作用是 判断 Base 是否为 Derived 的基类。
#include <iostream>
#include <type_traits>
class A {};
class B : A {};
class C {};
int main()
{
std::cout << std::boolalpha;
std::cout << "a2b: " << std::is_base_of<A, B>::value << '\n';
std::cout << "b2a: " << std::is_base_of<B, A>::value << '\n';
std::cout << "c2b: " << std::is_base_of<C, B>::value << '\n';
std::cout << "same type: " << std::is_base_of<C, C>::value << '\n';
}
a2b: true
b2a: false
c2b: false
same type: true