Search code examples
c++genericsgeneric-programminggeneric-type-argument

generic abstract type c++


I want to define a generic class in c++ that allow to execute my algorithm on any data. The problem is that this data can be anything (e.g. a vector of floats, a graph, etc). Is it possible to say in my class that the manipulated data is of type T which can be anything ? Then the user of my class will have to implement some methods of my class relative to manipulating his data (e.g. depending on his data he define how to do a sum of two data, etc ...)

Edit:

How is it possible then to instantiate the class template and call its method ? I have an error when I do:

MyClass<int, int> tst();
tst.test(3, 4); // or even with tst.test<int, int>(3, 4);

Error: request for member 'test' in 'tst', which is of non-class type 'MyClass()'

The class if defined as:

#include <iostream>
#include <boost/graph/adjacency_list.hpp>

using namespace std;
using namespace boost;

template<typename T1, typename T2>
class MyClass
{
    public:
        MyClass();
        virtual ~MyClass();
        void test(T1 p, T2 s);

    protected:
        struct NodeData
        {
            T1 var1;
            T2 var2;
            int var3;
        };

        struct EdgeData
        {
            int var;
        };

        typedef adjacency_list<setS, setS, undirectedS, NodeData, EdgeData> Graph;
        typedef typename Graph::vertex_descriptor NodeDataID;
        typedef typename Graph::edge_descriptor EdgeDataID;
        typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;

        Graph g;
};

template<typename T1, typename T2>
void MyClass<T1, T2>::test(T1 arg1, T2 arg2)
{
    NodeDataID nId = add_vertex(g);
    g[nId].anything = "but anything is not in struct NodeData !";
    g[nId].var1 = arg1;
    g[nId].var2 = arg2;
    g[nId].var3 = 55;
}

template<typename T1, typename T2>
MyClass<T1, T2>::MyClass()
{
    // ...
}

template<typename T1, typename T2>
MyClass<T1, T2>::~MyClass()
{
    // ...
}

Solution

  • As @Als comments, you're perfectly describing a class template.

    You can get a good leg up on the subject at http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fclass_templates.htm