在编译时根据模板参数安排类结构

Arranging Class Structure at Compile Time according to Template Parameters

本文关键字:参数 结构 编译      更新时间:2023-10-16

是否可以在c++中包含/排除基于模板参数的成员变量?

下面是一个例子:

template< class T >
class RealNumber
{
    T real;
};
template< class T >
class ComplexNumber
{
    T real;
    T imag;
};

由于它们有许多共同的属性,只使用一个类来表示一个数字(带有额外的模板参数)可以防止一些代码重复。

我想做的是像

这样的东西
template< class T , class U >
Number
{
    T real;
    // If U is not void
    U imag;
}

如果第二个参数为void,则没有名为imagg的成员,结果是:

sizeof( Number< T , void > ) == sizeof( T )

我尝试了enable_if,但是没有得到任何结果。

如果这是不可能的,有什么hack可以使它成为可能吗?

typedef NullType struct {} NullType;
template< class T , class U = NullType>
class Number
{
  T real;
  U image;
}

检查继承技巧是否适合您:

template<class T, class = void >
class RealNumber
{
  protected: T real;
};
template<class T, class U>
class ComplexNumber : public RealNumber<T>
{
  U imag;
};

这个答案是不完整的,只展示了如何使用enable_if来专门化类模板。

template<class T,class U,class Enable = void>
class Number
{
  T real;
  T imag;
};
template<class T,class U>
class Number<T,U,typename std::enable_if<std::is_void<U>::value>::type>
{
  T real;
};

具体实现取决于问题的确切性质。例如,

  • 如果允许RealNumber到ComplexNumber转换(即is_a关系),您可以考虑从一个实现继承到另一个实现。
  • 要重用大量属性,可以在私有基类中实现公共部分。
  • 根据具体问题,可以检查模板参数U是否真的需要。还有,实数Number<int,void>Number<int>的首选语法应该是什么。等。

很难说你想说什么,但这里有一个大致的框架:

template <typename T> class Number
{
  template <typename S> class Adder
  {
    typedef S type;
    static type add(type a, type b) { return a + b; }
  };
  template <typename U, typename W> class Adder<std::pair<U,W>>
  {
    typedef typename std::pair<U,W> type;
    static type add(type a, type b) { return type(a.first + b.first, a.second + b.second); }
  };
  T val;
public:
  T operator+(const T rhs) { return Adder<T>::add(val, rhs); }
};

请注意,大多数标准库数值函数已经为std::complex类型重载了,因此您可能需要考虑一下是否真的需要自己编写这些。

用法:Number<int>, Number<double>, Number<std::pair<double, double>> .