使用模板计算

本文介绍了模板计算的相关知识,包括枚举hack、next M和next N的概念,以及模板特化和模板默认参数的运用。提供了示例代码帮助理解。
摘要由CSDN通过智能技术生成

直接上代码如下

知识点

  • enum hack
  • next M and next N
  • 模板特化
  • 模板默认参数
  • printt不相关,
// 测试可变模板
void printt()
{

}

template<typename T, typename...Types>
void printt(const T& n, const Types&... args)
{
  std::cout << n << std::endl;
  printt(args...);
}

template<int n, int m>
struct nextN
{
  enum 
  {
    value = (n % m != 0)* n
  };
};

template<int n, int m>
struct nextM
{
  enum 
  {
    value = m*m > n ? -1 : m+1
  };
};

template<int n, int m=2>
struct testN
{
  enum
  {
    value = testN<nextN<n, m>::value, nextM<n, m>::value>::value
  };
};

template<int n>
struct testN<n, -1>
{
  enum
  {
    value = true
  };
};

template<int m>
struct testN<0, m>
{
  enum
  {
    value = false
  };
};

int main()
{

  std::cout << "nextN: " << std::endl;
  std::cout << nextN<16, 8>::value << std::endl;
  std::cout << nextN<8, 2>::value << std::endl;
  std::cout << nextN<7, 2>::value << std::endl;
  std::cout << "-----------------" << std::endl;

  std::cout << testN<100, 2>::value << std::endl;
  std::cout << testN<99, 2>::value << std::endl;
  std::cout << testN<97, 2>::value << std::endl;
  std::cout << "-----------------" << std::endl;

  std::cout << testN<100>::value << std::endl;
  std::cout << testN<99>::value << std::endl;
  std::cout << testN<97>::value << std::endl;
  std::cout << "-----------------" << std::endl;

  printt("a", 1, 22.3, "asdfasdf", 'd');

  system("pause");
 }

参考: https://www.cnblogs.com/devymex/p/3326793.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值