1.一个简单的计算质数的例子
template<unsigned Prime, unsigned U>class DoIsPrime {
public:
static constexpr bool value = (((Prime % U) != 0) && (DoIsPrime<Prime, U - 1>::value));
};
template<unsigned Prime>class DoIsPrime<Prime,2> {
public:
static constexpr bool value = (Prime % 2 != 0);
};
template<unsigned Value>class IsPrime{
public:
static constexpr bool value = DoIsPrime<Value, Value / 2>::value;
};
template<>
class IsPrime<(unsigned)0> {
public:
static constexpr bool value = false;
};
template<>
class IsPrime<1> {
public:
static constexpr bool value = false;
};
template<>
class IsPrime<2> {
public:
static constexpr bool value = true;
};
template<>
class IsPrime<3> {
public:
static constexpr bool value = true;
};
这个例子就是编译期运行的
2.计算和constexpr
这是一个非模板的函数
constexpr bool isPrime(unsigned int p){
}
//如果const bool b = isPrime(9);这个时候是在运行期运行的如果加上命名空间就是在编译期运行的
//如果constexpr bool b = isPrime(9) 这个是在编译期运行的
3.关于sfinae 什么是sfinae翻译成中文就是替换时的错误不是错误 举一个例子
template<typename T,size_t N>
void func(T(&)[N]){//数组的模板调用func的overload
}
template<typename T>
void func(T t){
t.size();
}
//当调用int arr[10];func(arr);这个时候第二个调用方式会发现arr没有size成员函数但是编译器并不会报错,这也就是sfinae.
3.表达式sfinae和decltype
template<typename T>
auto func(T t)->decltype(void(t.size()),T::size_type()){
}