Pregunta

I currently have a class defined in C++ which includes a C-preprocessor variable to switch on/off a certain feature:

A.hh

class A : public B {
  //...
#ifdef PPVAR
  int _i;
#endif

public: 
  A();
  //...
};

A.cc

A::A()
#ifdef PPVAR
  : B(1)
#else
  : B(2)
#endif
  {}

which affects the member variables and the initialization of the superclass. Currently I switch between the cases by including/excluding "-DPPVAR" in my c++ compiler flags. However, it would be much more desirable to have both implementations available simultaneously. I could in principle duplicate these source files (A_on.[hh,cc], A_off.[hh,cc]) but since they have so much in common this seems very inelegant. Because the flag influences the members and the constructor of the superclass I don't see an easy way of controlling this feature by simply introducing for instance a global variable bool switchFeature = [T|F] and using

if (switchFeature) {
  //...
} else {
 //...
}

everywwhere. If this were possible it would be my method of choice and I would love to hear your solution to this!

As an alternative (although doubling the number of classes) I thought maybe one could compile this source twice, once with "-DPPVAR" and once without and producing two object files A_on.o, A_off.o, but somehow I would still need to duplicate my header for this to work and would require more modifications in the rest of the code.

I'd appreciate any insight and hints on how I could tackle this problem

¿Fue útil?

Solución

Make your class A template from int.

template<int PPVAR_val = 1>
class A : public B {
  //number of members can also differ for partial specializations
  int _i;

public: 
  A();
  //...
};

A.cpp

template<int PPVAR_val>
A::A()
  : B(PPVAR_val)
  {}

Otros consejos

You should create a child to A and add virtual methods if some code differ between A and its child

A.hh

class A : public class B {

// Common attributes and Functions
...

protected:
A(int ppvar) : B(ppvar) {}; // Not public
public:
A() : B(1) {};

virtual method(); // Method that differ between A and its Child
...
};

class A2 : public class A {
// Attributes only needed by A2
...
public:
A2() : A(2) {};

method(); // Say that A2 will use its own implementation of method
};

main.cc

int main(void)
{
bool PPVar = ...;
A    *a;
if (PPVar)
     a = new A();
else
     a = new A2();

a->method();
return (0);
}

An abstract class A with two child AOn and Aoff also.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top