Jimm
Jimm

Reputation: 8505

How to instantiate class with different arguments

I need a way to calculate various types of anomalies in a dataset. hence, i was thinking of having a generic Anomaly interface, which defines the interface for concrete Anomalies. Then my application can simply use the interface to iterate over various concrete strategies.

The main problem i am running into is that the construction of concrete Anomalies requires different inputs. For example,

class Anamoly
{
public:
  template <typename T> 
  virtual Anamoly * getInstance(T &) = 0;
  virtual void processAnamoly() = 0;
  virtual bool containsAnamoly() = 0;
  virtual void logAnamoly() = 0;
};

Since templates functions cannot be virtual, is there a way to get around this issue, which would allow construction of concrete Anomalies with different inputs, yet, allow me to use the generic interface for rest of the behavior?

Upvotes: 3

Views: 194

Answers (1)

Vincent Fourmond
Vincent Fourmond

Reputation: 3278

Virtual function with templates parameters isn't going to work, but you could use a static template function:

class Anomaly {
public:
  template <typename T> 
  static Anomaly * getInstance(T &);
  virtual void processAnamoly() = 0;
  virtual bool containsAnamoly() = 0;
  virtual void logAnamoly() = 0;
};

Then, whenever you define a relevant subclass, implement Anomaly::getInstance(), such as in myanomaly.cpp:

class MyAnomaly : public Anomaly {
  // implement virtual functions
};

Anomaly * Anomaly::getInstance(MyType & t) {
  return new MyAnomaly(t);
};

The advantage of this approach is that you don't need to touch the anomaly.h header file whenever you add a new class, and you don't need to expose subclasses outside of their definition file. The downside is type errors get only caught at link time and not at compile time.

Upvotes: 1

Related Questions