By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,962 Members | 2,036 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,962 IT Pros & Developers. It's quick & easy.

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

P: n/a
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 Tclass Foo {
public:
Foo(int param) { _algorithm.Init(param); }
void do_algorithm(vector<inta) {
_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<inta) = 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<inta) {}
virtual void Init(int param) {}
};

Aug 16 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 16 Srp, 02:48, newbie <mitbb...@yahoo.comwrote:
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 Tclass Foo {
public:
Foo(int param) { _algorithm.Init(param); }
void do_algorithm(vector<inta) {
_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<inta) = 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<inta) {}
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.

Aug 16 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.