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

标签 c++ c++11 conditional-compilation

我正在尝试创建一个具有条件成员的结构,这意味着不同的成员只存在于特定的特化中。但是,我希望这些类(class)尽可能快。我已经尝试了三种不同的方式:

方式一:

 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;
 };
  • 缺点:每个专业重复代码。

方式二:

 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;
 };
  • 优点:代码少。
  • 缺点:使用 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;
 };
  • 特长:写一次代码;当 with_intfalse 时,字段 m_int 的大小为 0(几乎与 gcc 4.7.2 一起使用)。
  • 优点:更多地使用模板(降低可读性),我不确定编译器如何处理大小为 0 的成员。我确实不知道大小为 0 的字段在多大程度上是危险的或有意义的。重复的构造函数,但也许这是可以避免的。

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

最佳答案

你考虑过继承吗?

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
};

关于C++11:条件编译:成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15473643/

相关文章:

c++ - lambda 的模板参数推导

rust - 在库模块和它的测试模块之间共享数据

c++ - 如何在 Metro 应用程序中打印到 C++ 中的 Visual Studio 11 控制台/日志?

c++ - any_of 与 find_if

c++ - 提升几何圆段相交

c++ - boost::optional - 将 boost::in_place 用于构造函数通过引用获取其他对象的对象

使用子句中的 Delphi 条件编译

objective-c - 用于配置的 XCode 预处理器宏?

c++ - 如何在函数指针中模板化参数?

c++ - 使用 for 循环并查找而不是 set_intersection?