C++ Meta Programming

潜行狙击 2014-02-12 10:45:10
网上看到一个99乘法表,代码不全不知道这个代码怎么写的

#include

using namespace std;

inline void printLine(int i, int j) {
cout << i << " * " << j << " = " << i * j << endl;
}

template
struct Line {
inline static void print() {
Line::print();
printLine(I, J);
}
};

template
struct Line {
inline static void print() {
printLine(I, 1);
}
};

template
struct Group {
inline static void print() {
Group::print();
cout << endl;
Line::print();
}
};

template
struct Group {
inline static void print() {
Line<1, NUM>::print();
}
};

template
struct Meta99 {
inline static void print() {
Group::print();
}
};

int main() {
Meta99<20>::print();
return 0;
}
...全文
166 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
潜行狙击 2014-02-13
  • 打赏
  • 举报
回复
多谢ri_aje
huangxiangbo316 2014-02-13
  • 打赏
  • 举报
回复
用VS2008 编译了ri_aje能够通过,并得到9*9乘法表 楼主的编译不通过。 ri_aje 的代码可以简单理解为一种递归。
ri_aje 2014-02-13
  • 打赏
  • 举报
回复

#include <iostream>

inline void print_item (size_t const i, size_t const j)
{
 std::cout << i << "x" << j << "=" << i * j << " ";
}

template <size_t I, size_t J>
struct line_t
{
 inline static void print ()
 {
  print_item(I,J);
  line_t<I+1,J>::print();
 }
};

template <size_t I>
struct line_t<I,I>
{
 inline static void print ()
 {
  print_item(I,I);
 }
};

template <size_t N>
struct table_t
{
 inline static void print ()
 {
  table_t<N-1>::print();
  std::cout << std::endl;
  line_t<1,N>::print();
 }
};

template <>
struct table_t<1>
{
 inline static void print ()
 {
  line_t<1,1>::print();
 }
};

template <size_t N>
struct meta99
{
 inline static void print ()
 {
  table_t<N>::print();
  std::cout << std::endl;
 }
};

int main ()
{
 meta99<9>::print ();
 return 0;
}

buyong 2014-02-13
  • 打赏
  • 举报
回复
你给的代码完全没法编译
潜行狙击 2014-02-13
  • 打赏
  • 举报
回复
我就是没有看明白这段代码怎么完成99乘法表,想请教一下高人解读一下
潜行狙击 2014-02-13
  • 打赏
  • 举报
回复
完整的元编程代码,应该是怎么写的
derekrose 2014-02-13
  • 打赏
  • 举报
回复
什么叫不知道怎么写的
潜行狙击 2014-02-13
  • 打赏
  • 举报
回复
没有知道吗?
潜行狙击 2014-02-12
  • 打赏
  • 举报
回复
要填模板参数吧
偏爱风流 2014-02-12
  • 打赏
  • 举报
回复
template<>
潜行狙击 2014-02-12
  • 打赏
  • 举报
回复
本身程序就不对?

64,682

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧