C++11:条件编译:成员

Per*_*-lk 4 c++ conditional-compilation c++11

我正在尝试使用条件成员创建一个结构,这意味着不同的成员仅存在于特定的专业化中。但是,我希望这门课尽可能快。我以三种不同的方式尝试过:

方式一:

 template<typename T, bool with_int = false>
 struct foo
 {
     template<typename... Args>
     foo(Args&&... args) : m_t(forward<Args>(args)...)
     {}

     T m_t;
 }

 template<typename T>
 struct foo<T, true>
 {
     template<typename... Args>
     foo(Args&&... args) : m_t(forward<Args>(args)...), m_id(0)
     {}

      T m_t;
      int m_id;
 };
Run Code Online (Sandbox Code Playgroud)
  • 缺点:每个专业都有重复的代码。

方式二:

 template<typename T, bool with_int = false>
 struct foo
 {
     template<typename... Args>
     foo(Args&&... args) : m_t(forward<Args>(args)...)
     {}

     virtual ~foo() {}

     T m_t;
 }

 template<typename T>
 struct foo<T, false> : public foo<T>
 {
      using foo<T>::foo;

      int m_id = 0;
 };
Run Code Online (Sandbox Code Playgroud)
  • 优点:代码少。
  • 缺点:vtables/inheritance/etc的使用:更多的时间在构建或访问成员?但是,换句话说,我不会假装使用“引用”到基类。这种方法的真正优点或缺点是什么?

方式三

 using nil_type = void*;
 using zero_type = nil_type[0];

 template<typename T, bool with_int = false>
 struct foo
 {
    template<typename... Args, typename = typename enable_if<with_int>::type>
    foo(Args&&... args) : m_t(forward<Args>(args)...), m_int(0)
    {}

    template<typename... Args, typename = typename enable_if<!with_int>::type>
    foo(Args&&... args) : m_t(forward<Args>(args)...)
    {}        

    T m__t;
    typename conditional<with_int, int, zero_type>::type m_int;
 };
Run Code Online (Sandbox Code Playgroud)
  • 优点:一次编写代码;当with_intis 时false,字段的m_int大小为 0(几乎使用 gcc 4.7.2)。
  • 优点:更多使用模板(降低可读性),我不确定编译器如何处理大小为 0 的成员。我确实不知道大小为 0 的字段在多大程度上是危险的或有意义的。重复构造函数,但也许这是可以避免的。

最好的方法或方法是什么?

Dan*_*rey 5

你考虑过继承吗?

template< bool >
struct foo_int_base
{
  // stuff without the int
  void f(); // does not use m_id
};

template<>
struct foo_int_base< true >
{
  // stuff with the int
  int m_id = 0;
  void f(); // uses m_id
};

template< typename T, bool with_int = false >
struct foo : foo_int_base< with_int >
{
  // common stuff here
};
Run Code Online (Sandbox Code Playgroud)