【问题标题】:Is it possible to use C++ template to control code generation?是否可以使用 C++ 模板来控制代码生成?
【发布时间】:2015-12-22 08:49:04
【问题描述】:

是否可以使用 C++ 模板来控制代码生成?

类似(伪代码...)

template<int i, int j> void f() {
#if i > j
#define
  //code...
#else
  //code...
#endif
}

(我开始习惯使用模板,但我想知道它们有多强大)。

谢谢!

【问题讨论】:

标签: c++ templates macros code-generation


【解决方案1】:

像这样的元编程通常结合专业化和重载来完成。在您的情况下,标签调度(将值转换为类型)是一个可行的解决方案:

#include <type_traits>

void f_impl(std::true_type) { /* ... */ }
void f_impl(std::false_type) { /* ... */ }

template <int i, int j> void f() {
  f_impl(std::integral_constant<bool, (i > j)>());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多