Is it necessary (design-wise) to define an abstract class as template's argument?

N

newbie

Here is my question:
I want to have a class, which requires a typename T with interface
"operate()" and "Init()" as its parameter.

template <class T> class Foo {
public:
Foo(int param) { _algorithm.Init(param); }
void do_algorithm(vector<int> a) {
_algorithm.operate(a);
....
}
private:
T _algorithm;
};

I understand this is not necessary to define an interface class (for
example, as long as DumbAlgrithm provide functions that Foo needs,
it's good). But I am thinking if having a class hierarchy helps code
maintenance. What's the normal approach in this case? Thanks a lot.

class AbstractAlgorithm {
public:
virtual void operate(vector<int> a) = 0;
virtual void Init(int param) = 0;
};

Then any class that actually used as parameter by Foo will be the sub
class of AbstractAlgorithm, e.g.,
class DumbAlgorithm : public AbstractAlgorithm {
public:
virtual void operate(vector<int> a) {}
virtual void Init(int param) {}
};
 
O

Ondra Holub

Here is my question:
I want to have a class, which requires a typename T with interface
"operate()" and "Init()" as its parameter.

template <class T> class Foo {
public:
Foo(int param) { _algorithm.Init(param); }
void do_algorithm(vector<int> a) {
_algorithm.operate(a);
....
}
private:
T _algorithm;

};

I understand this is not necessary to define an interface class (for
example, as long as DumbAlgrithm provide functions that Foo needs,
it's good). But I am thinking if having a class hierarchy helps code
maintenance. What's the normal approach in this case? Thanks a lot.

class AbstractAlgorithm {
public:
virtual void operate(vector<int> a) = 0;
virtual void Init(int param) = 0;

};

Then any class that actually used as parameter by Foo will be the sub
class of AbstractAlgorithm, e.g.,
class DumbAlgorithm : public AbstractAlgorithm {
public:
virtual void operate(vector<int> a) {}
virtual void Init(int param) {}

};

If you have common abstract class, you do not need to use template for
such issue. You can simply pass some instance (or reference to
instance or pointer to instance) of AbstractAlgorithm to constructor
of Foo and then use it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top