部分专业化与继承。我可以避免继承吗?

时间:2014-05-07 19:13:49

标签: c++ templates c++11 traits partial-specialization

我正在编写一个矢量类,我希望它具有以下特征:

  1. 尽可能在堆栈上使用静态分配(以避免为了提高效率而调用new)。
  2. 如果用户更喜欢提供先前分配的数组,则能够从指针实例化。
  3. 需要将类轻松转换为简单指针。这允许在C。
  4. 中使用以前编写的例程

    使用我提出的解决方案在下面找到这个简单的测试问题。我使用继承,因此Vector继承自Vector_base,它为所有向量提供了一个通用接口(纯虚拟)。 然后我定义了一个空类Vector,它允许我使用部分特化来拥有不同的存储方案;静态或动态。

    这背后的想法是我只想让vector成为旧式静态数组的C ++包装器。

    我喜欢下面的实现。我想保留我想出的主界面。

    我不喜欢的是sizeof(Vector3)= 32,当在C中时,三个双精度的矢量是24个字节。原因是虚拟表的额外8个字节。

    我的问题:我可以以某种方式提出另一种设计,它会为我提供相同的接口,但矢量只有24个字节吗?

    汇总:

    1. 我想要一个24字节的Vector3,如C。
    2. 我仍然希望拥有任意大的矢量(使用<double,n>
    3. 我想保留main()中使用的界面。
    4. 我可以使用类似特征或策略的编程习惯吗?我是新手,我不知道他们是否能提供解决方案。

      在下面找到我的小测试代码:

      #include <iostream>
      using namespace std;
      
      #define TRACE0(a) cout << #a << endl; a;
      #define TRACE1(a) cout << #a "=[" << a << "]" << endl;
      
      enum alloc_type {Static,Dynamic};
      
      template <class T>
      class Vector_base{
      public:
        Vector_base(){}
        virtual operator T*() = 0;
        virtual T operator[](int i)const = 0;
        virtual T& operator[](int i) = 0;
        virtual int size() const = 0;
        friend ostream& operator<<(ostream &os,const Vector_base& v){
          for (int i=0; i<v.size(); i++)
            cout << v[i] << endl;
          return os;
        }
      };
      
      // base template must be defined first
      template <class T, int n,alloc_type flg=Static>
      class Vector{};
      
      //Specialization for static memory allocation.
      template <class T, int n>
      class Vector<T,n,Static>: public Vector_base<T>{
      public:
        T a[n];
      public:
        Vector() { 
          for (int i=0; i<n; i++) a[i] = 0; 
        }
        int size()const{return n;}
        operator T*(){return a;}
        T operator[](int i)const {return a[i];}
        T& operator[](int i){return a[i];}
      };
      
      //Specialization for dynamic memory allocation
      template <class T,int n>
      class Vector<T,n,Dynamic>: public Vector_base<T>{   //change for enum. flg=0 for static. flg=1 for dynamic. Static by default
      public:
        T* a;
      public:  
        Vector():a(NULL){
        }  
        Vector(T* data){ //uses data as its storage
          a = data;
        }
        int size()const{return n;}
        operator T*(){return a;}
        T operator[](int i)const {return a[i];}
        T& operator[](int i){return a[i];}
      };
      
      //C++11 typedefs to create more specialized three-dimensional vectors.
      #if (__cplusplus>=201103L)
      template <typename Scalar,alloc_type flg=Static>
      using Vector3 = Vector<Scalar,3,flg>;
      #else
      #error A compiler with the C++2011 standard is required!
      #endif
      
      int main(){
      
        cout << "Testing Vector3: " << endl;
      
        //Vector<double,3> v3;
        Vector3<double> v3;
        TRACE0(cout << v3 << endl;);
        TRACE1(sizeof(v3));
      
        //Vector<double,3,Dynamic> v0(v3);
        Vector3<double,Dynamic> v0(v3); //calls Vector<double,3,Dynamic>::Vector(double*) and uses the conversion operator on v3.
        TRACE1(sizeof(v0));
        TRACE1(sizeof(double*));
      
        TRACE0(v3[1] = 2.1;);
        TRACE0(cout << v0 << endl;);
      
        return 0;
      }
      

5 个答案:

答案 0 :(得分:8)

您想要的所有功能都以标准形式提供,或者可以插入现有的标准扩展点。

  

尽可能在堆栈上使用静态分配(以避免为了提高效率而调用new)。

std::array<T, N>。它是C数组上的C ++包装器,具有所有相同的特性。

  

如果用户更喜欢提供先前分配的数组,则能够从指针实例化。

认识分配者。您可以编写满足已经分配内存的需求的分配器,然后只需使用std::vector。这样的分配器正在考虑未来的标准以及其他分配器增强功能,如多态分配器。

  

该类需要轻松转换为简单的指针。这允许在C中使用以前编写的例程。

std::vectorstd::array都认为这是一个微不足道的事。

如果您想在运行时提供此选择,请考虑boost::variant。滚动你自己的歧视联盟 - 不建议。

答案 1 :(得分:1)

如果我理解正确的话,像LLVM's SmallVector这样的话似乎符合要求。它有一个模板参数,声明要在堆栈上分配的最大大小,并且只有当它超出该范围时才切换到堆内存。

如果它不能直接适合您的界面,我相信实施对于自己编写类似的内容非常有用。

答案 2 :(得分:0)

您正在讨论两种用于查找数据的策略:内联作为小型数组优化,或通过间接指向动态分配的缓冲区。

有两种方法可以选择策略:使用静态类型信息,或动态。动态选择需要存储来指示任何特定向量是使用静态策略还是动态策略。

对于双精度矢量,您可以在第一个元素(NaN编码)中使用非法值来指示动态策略生效(指针需要与其余元素重叠存储,使用联合这一点)。

但在其他数据类型中,所有可能的位模式都是有效的。对于那些,您将需要额外的存储空间来选择策略。您可能知道某个特定问题,该值范围不需要特定位,并且可以用作标志。但是没有适用于所有数据类型的通用解决方案。

您可能希望了解“小字符串优化”的实现。当数据足够小以直接存储在对象内部时,他们正在对改进的引用局部性进行相同的权衡,并且通常也试图避免使用模式空间而不是必要的。

有一件事是肯定的。为了避免显着增加空间需求,您需要紧密耦合。没有专业化,没有继承,只有一个实现两种策略的整体类。

答案 3 :(得分:0)

好的伙计们。这花了我一整天,但这是我提出的解决方案,它完全符合我的要求。请分享您对此解决方案的意见和建议。 当然我没有实现我想要的所有方法。我只实现了两个假点产品,以显示在编译时如何使用模板选择特定的C实现。

该计划比我想象的要复杂得多。我用来完成设计要求的基本概念是:

  1. 奇怪的重复出现的模板模式。
  2. 部分专业化
  3. 性状
  4. 使用模板进行编译时选择(请参阅我如何确定要使用的点产品实现)。
  5. 再次,谢谢,请评论!!见下面的代码

    #include <iostream>
    using namespace std;
    #include <type_traits>
    
    //C++11 typedefs to create more specialized three-dimensional vectors.                                                                                                                                                                                                                                                       
    #if (__cplusplus<201103L)
    #error A compiler with the C++2011 standard is required!
    #endif
    
    template<class T>
    struct traits{};
    
    #define TRACE0(a) cout << #a << endl; a;
    #define TRACE1(a) cout << #a "=[" << a << "]" << endl;
    
    enum {Dynamic = -1};
    
    template<typename T,int n>
    struct mem_model{
      typedef T array_model[n];
    };
    
    //Specialization to Dynamic                                                                                                                                                                                                                                                                                                  
    template<typename T>
    struct mem_model<T,Dynamic>{
      typedef T* array_model;
    };
    
    template<class derived_vector>
    struct Vector_base: public traits<derived_vector>{ //With traits<derived_vector> you can derive the compile time specifications for 'derived_vector'                                                                                                                                                                         
      typedef traits<derived_vector> derived;
      typedef typename traits<derived_vector>::Scalar Scalar;
    
    public:
      inline int size()const{ //Calling derived class size in case a resize is done over a dynamic vector                                                                                                                                                                                                                        
        return static_cast<const derived_vector*>(this)->size(); //derived_vector MUST have a member method size().                                                                                                                                                                                                              
      }
    
      inline operator Scalar*(){return a;} //All vectors reduce to a Scalar*                                                                                                                                                                                                                                                     
    
      inline bool IsStatic()const{return (n==Dynamic)? false: true;}
    
      inline int SizeAtCompileTime()const{return n;} //-1  for dynamic vectors                                                                                                                                                                                                                                                   
    
    protected:
      using derived::n; //compile time size. n = Dynamic if vector is requested to be so by the user.                                                                                                                                                                                                                            
      typename mem_model<Scalar,n>::array_model a;  //All vectors have a Scalar* a. Either static or dynamic.                                                                                                                                                                                                                    
    };
    
    //Default static                                                                                                                                                                                                                                                                                                             
    template<typename Scalar,int n>
    class Vector:public Vector_base<Vector<Scalar,n> >{ //Vector inherits main interface from Vector_base                                                                                                                                                                                                                        
    public:
      //Constructors                                                                                                                                                                                                                                                                                                             
      Vector(){
        //do nothing for fast instantiation                                                                                                                                                                                                                                                                                      
      }
      Vector(const Scalar& x,const Scalar& y,const Scalar& z){
        a[0] = x; a[1] = y; a[2] = z;
      }
    
      //                                                                                                                                                                                                                                                                                                                         
      inline int size()const{return n;}
    
    private:
      using Vector_base<Vector<Scalar,n> >::a;
    
    };
    
    //Traits specialization for Vector. Put in an inner_implementation namespace                                                                                                                                                                                                                                                 
    template<typename _Scalar,int _n>
    struct traits<Vector<_Scalar,_n> >{
      typedef _Scalar Scalar;
      enum{
        n = _n
      };
    };
    
    double clib_dot_product_d(const int n,double* a,double* b){
      double dot = 0.0;
      for(int i=0;i<n;i++)
        dot += a[i]*b[i];
      return dot;
    }
    float clib_dot_product_f(const int n,float* a,float* b){
      cout << "clib_dot_product_f" << endl;
      return 1.0;
    }
    
    template<typename Scalar>
    struct dot_product_selector{};
    
    template<>
    struct dot_product_selector<double>{
      template<class derived1,class derived2>
      static double dot_product(Vector_base<derived1> &a,Vector_base<derived2> &b){
        return clib_dot_product_d(a.size(),a,b);
      }
    };
    
    template<>
    struct dot_product_selector<float>{
      template<class derived1,class derived2>
      static float dot_product(Vector_base<derived1> &a,Vector_base<derived2> &b){
        return clib_dot_product_f(a.size(),a,b);
      }
    };
    
    template<class derived1,class derived2>
    typename Vector_base<derived1>::Scalar dot_product(Vector_base<derived1> &a,Vector_base<derived2> &b){
      //run time assert checking the two sizes are the same!!                                                                                                                                                                                                                                                                    
    
      //Compile time (templates) check for the same Scalar type                                                                                                                                                                                                                                                                  
      static_assert( std::is_same<typename Vector_base<derived1>::Scalar,typename Vector_base<derived2>::Scalar>::value,"dot product requires both vectors to have the same Scalar type");
      return dot_product_selector<typename Vector_base<derived1>::Scalar>::dot_product(a,b);
    }
    
    #if 0
    template <typename Scalar,alloc_type flg=Static>
    using Vector3 = Vector<Scalar,3,flg>;
    #endif
    
    int main(){
    
      cout << "Testing Vector3: " << endl;
    
    
      Vector<double,3> as;
      Vector<double,Dynamic> ad;
    
      TRACE1(sizeof(as));
      TRACE1(sizeof(ad));
    
      TRACE1(as.SizeAtCompileTime());
      TRACE1(ad.SizeAtCompileTime());
    
      Vector<double,3> u(1,2,3),v(-1,1,5);
      Vector<float,3> uf,vf;
      TRACE1(dot_product(u,v));
    
      dot_product(uf,vf);
    
      //dot_product(u,vf); //this triggers a compile time assertion using static_assert                                                                                                                                                                                                                                          
    
      return 0;
    }
    

答案 4 :(得分:-1)

您可以将Vector模板专精化简化为...

template <class T, std::size_t Size = -1>
class Vector {
    // The statically allocated implementation
};

template <class T>
class Vector<T, -1> {
    // The dynamically allocated implementation
};

实现可能是围绕std::vectorstd::array的薄包装。

编辑:这避免了魔法常数...

template<typename T = void>
class Structure {};

template<typename T, std::size_t Size>
class Structure<T[Size]> {
    T data[Size];
    // The statically allocated implementation
};

template<typename T>
class Structure<T[]> {
    T * pData;
public:
    Structure(std::size_t size) : pData(new T[size]) {}
    ~Structure() { delete[] pData; }
    // The dynamically allocated implementation
};

像这样实例化......

Structure<int[]> heap(3);
Structure<int[3]> stack;

编辑:或者使用这样的政策...

class AllocationPolicy {
protected:
    static const std::size_t Size = 0;
};
template<std::size_t Size_>
class Static : AllocationPolicy {
protected:
    static const std::size_t Size = Size_;
};
class Dynamic : AllocationPolicy {
protected:
    static const std::size_t Size = 0;
};

template <typename T, typename TAllocationPolicy = Dynamic>
class Vector : TAllocationPolicy {
    static_assert(!std::is_same<typename std::remove_cv<TAllocationPolicy>::type, AllocationPolicy>::value && std::is_base_of<AllocationPolicy, TAllocationPolicy>::value, "TAllocationPolicy must inherit from AllocationPolicy");
    using TAllocationPolicy::Size;
public:
    T data[Size];
};

template <typename T>
class Vector<T, Dynamic> : private Dynamic {
    T * data;
public:
    Vector(std::size_t size) : data(new T[size]) {}
    ~Vector() { delete [] data; }
};