Search code examples
c++nvccclass-template

c++ inherit from a template struct


I have two class to define some operations and keep a record of matrix rows and cols. One for host, another for device.

struct device_matrix {

     device_vector<double> data;
     int row;
     int col;

     // constructors
     device_matrix() ... 

     // some matrix operations
     add()...

}


struct host_matrix {
     host_vector<double> data;
     int row;
     int col;

     // constructors
     host_matrix() ... 

     // some matrix operations
     add()...

}

The base class should look like:

template<typename T>
struct base_matrix {
    T data;
    int row;
    int col;

    // no constructors

    // some matrix operations
    add()...
}

But except for the type of data and constructors, other staff are the same. I have to achieve three goals, one is to specialize type T to device_vector or host_vector, another is write different constructors for both structs, and also inherit operation methods. How can I do that at the same time?

Thanks!


Solution

  • How about

    template<template<typename T> class V>
    struct base_matrix
    {
        V<double> data;
        ...
        virtual void add(...) = 0;
    };
    
    struct host_matrix : base_matrix<host_vector>
    {
        host_matrix() { ... }
        ...
        void add(...) { ... }
    };
    

    If you can't use a template template, then like this:

    template<typename V>
    struct base_matrix
    {
        V data;
        ...
        virtual void add(...) = 0;
    };
    
    struct host_matrix : base_matrix<host_vector<double>>
    {
        host_matrix() { ... }
        ...
        void add(...) { ... }
    };