在编译时删除/插入代码,在C ++中没有重复 [英] Remove/Insert code at compile time without duplication in C++

查看:263
本文介绍了在编译时删除/插入代码,在C ++中没有重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板类,它接受几种类型。一种类型只是确定政策。

I have a template class that is taking in a couple of types. One type is there just to determine policies. That class determines how a function may work in certain cases.

我们假设这是一个函数:

Let's say this is one of the function:

/* this code is part of a class */

    template <typename T, typename T_Policy> // Not important but just showing the template parameters of the class

    void Allocate(unsigned int numElements)
    {
      // Some code here
      while (someCondition) // Other functions don't have the loop, this is just an example
      {
        // Some code here

        if (T_Policy::trackElements) { /* some code here */ }
        if (T_Policy::verbose) { /* some code here */ }
        if (T_Policy::customManager) { /* some code here */ }
        /* and a few other policies */
      }
      // Some more code here
    }

我想使用策略的代码行编译出来,而不是依赖 if 语句。一个明显的方法是将while循环置于重载函数中,每个函数采用具有特定策略类型的虚拟对象。但这意味着大量的代码重复。类似的模板专门化方法也会导致代码重复。

I would like the lines of code that are using the policies to be compiled out instead of relying on if statements. One obvious way is to put the while loop in overloaded functions each taking a dummy object with a specific policy type. But that means a lot of code duplication. Similar approaches with template specialization will result in code duplication as well.

有没有办法编译代码而不重复代码?

Is there a way to compile out the code without code duplication?

推荐答案

您随时可以更改代码

   if (T_Policy::trackElements) { /* some code here */ }

template <bool b>
void trackElementPhase() {
  /* some code here */
}

template <>
void trackElementPhase<false>() {} // empty body

 ... later in the code

     trackElementPhase<T_Policy::track_elements>();

当然 T_Policy :: track_elements 是这个的编译时间常数。

Of course T_Policy::track_elements has to be compile time constant for this.

但是,我不会打扰。编译器可能聪明到足以优化

However, I wouldn't bother. The compiler is likely clever enough to optimize out code in

   if (T_Policy::trackElements) { /* some code here */ }

如果条件是编译时常量。

if the condition is compile time constant.

这篇关于在编译时删除/插入代码,在C ++中没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆