首页 > 解决方案 > 基于#define变量类型的条件编译

问题描述

以下是我想要实现的剪辑版本。我正在对一个单词进行一些算术运算,我想__builtin_clrsb在它可用并且用户int用作单词类型时使用,否则使用慢速算法编译。__builtin_clrsb无论类型如何,以下都会编译WORD

代码使用 C++11,但在嵌入式系统上运行,因此我无法访问大多数std::设施。

#if !defined(WORD)
  #define WORD int
#endif

template<size_t S, typename word = WORD>
class my_class {
  ...
  ...
  ...

  size_t do_stuff(){
#if WORD == int && defined(__builtin_clrsb)
    //compile with  __builtin_clrsb
#else
   //comple with slow method
#endif
  }
};

标签: c++11gccclangc-preprocessor

解决方案


我认为你不应该这样做:

  size_t do_stuff(){
#if WORD == int && defined(__builtin_clrsb)
    //compile with  __builtin_clrsb
#else
    //comple with slow method
#endif
  }

相反,您应该使用 C++ 模板专业化来解决这个问题。

template<class D, size_t S, class word>
struct my_class_do_stuff_impl {
  D& self() { return *static_cast<D*>(this); }
  D const& self() const { return *static_cast<D const*>(this); }
  size_t do_stuff(){
    //compile with slow method
    //use `self()` instead of `this` to access members of `my_class`
  }
};
#if defined(__builtin_clrsb)
  template<class D, size_t S>
  struct my_class_do_stuff_impl<D,S,int> {
    D& self() { return *static_cast<D*>(this); }
    D const& self() const { return *static_cast<D const*>(this); }
    size_t do_stuff(){
      //compile with  __builtin_clrsb
      //use `self()` instead of `this` to access members of `my_class`
    }
  };
#endif
template<size_t S, typename word = WORD>
class my_class:
  public my_class_do_stuff_impl<my_class<S,word>, S, word>
{
  // don't include do_stuff here
  // if you call do_stuff, do this->do_stuff()
};

这样做有无数理由。一是WORDint 并不强制 my_classword成为int. 另一个是我们可以在预处理器之外执行此操作,所以我们应该这样做。


推荐阅读