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/

相关文章:

d - 如何检查变量是否在D中声明?

c++ - 使用 OpenSSL 从内存中读取原始 SSL/TLS 证书

c++ - 错误 : reference to ‘sword’ is ambiguous in armadillo and oracle occi compatibility issue

c++ - 如何在推导上下文中将 std::bind (或 lambda)转换为 std::function ?

c++ - Lambda 表达式

c++ - 用于 C++ 的整数区间容器,例如 RangeSet

iphone - 在XCode中编译多个目标时,如何确保某些文件不会包含在一个目标中

c++ - 将 _bstr_t 就地转换为 char 数组

templates - C++11 可变参数模板在仿函数中解包参数

c++ - 是否可以根据宏或变量有条件地编译/运行代码?