constexpr的使用

我们今天稍微介绍一下这个关键字的使用,概念都很简单,没什么好说的,我们用质数来做例子

#include<iostream>
#include<string>
template<unsigned p, unsigned d> // p:要检查的数字,d:当前除数
struct DoIsPrime {
	static constexpr bool value = (p % d != 0) && DoIsPrime<p, d - 1>::value;
};
template<unsigned p> // 如果除数为 2,则结束递归
struct DoIsPrime<p, 2> {
	static constexpr bool value = (p % 2 != 0);
};
template<unsigned p> // 主模板
struct IsPrime {
	// 从 p/2 开始用除数开始递归:
	static constexpr bool value = DoIsPrime<p, p / 2>::value;
};

//类模板特例化,防止这些特殊情况
template<>//
struct IsPrime<0> { static constexpr bool value = false; };
template<>
struct IsPrime<1> { static constexpr bool value = false; };
template<>
struct IsPrime<2> { static constexpr bool value = true; };
template<>
struct IsPrime<3> { static constexpr bool value = true; };

void test01() {
	int num[IsPrime<5>::value]{ 10 };	//因为编译期就已经得出结果,所以可以做数组下标
	std::cout << *num << std::endl;
	std::cout << IsPrime<21>::value << std::endl;
	std::cout << IsPrime<3>::value << std::endl;
}

//使用函数编译期判断
constexpr bool doIsPrime(unsigned p, unsigned d) // p: number to check, d: current
{
	return d != 2 ? (p % d != 0) && doIsPrime(p, d - 1) // check this and smaller
		: (p % 2 != 0); // end recursion if divisor is 2
}
constexpr bool isPrime(unsigned p)
{
	return p < 4 ? !(p < 2) // handle special cases
		: doIsPrime(p, p / 2); // start recursion with divisor fromp / 2
}

//c++14以后constexpr函数可以使用常规C++代码中大部分的控制结构,所以我们直接使用一个for循环也行
constexpr bool isPrime_(unsigned int p)
{
	for (unsigned int d = 2; d <= p / 2; ++d) {
		if (p % d == 0) {
			return false;
		}
	}
		return p > 1;
}

void test02() {
	std::cout << isPrime(21) << std::endl;
	std::cout << isPrime(3) << std::endl;

	std::cout << isPrime_(21) << std::endl;
	std::cout << isPrime_(3) << std::endl;
}
int main()
{
	//test01();	//类
	test02();	//函数
	return 0;
}

环境是MSVC  debug 禁止优化 C++20,你们的编译器至少要达到c++14

我们先把全部的代码贴出来,如果c++没有一定水平的话自己去补习一下,这里大量用到了递归,我们写个两种主要的,函数和类。

没啥好讲的,请靠自己

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值