Reputation: 5545
I am trying to implement the following behavior:
I have two classes, inheriting from the same class. Both of them will perform some work, changing their state at some point, and at some point, this state needs to be checked. The check is similar, for both classes in that in both tests, we compare the actual state with the desired state. The only thing different is the desired state, which is class dependent.
In code, a minimal example of how I achieve this is like so:
#include <iostream>
class A {
public:
static int x = 1;
int y;
A(int _y): y(_y) {}
void test() {
bool passed = x == y;
std::cout << "Test" << (passed ? "" : " not") << " passed\n";
}
};
class B : public A {
public:
B(int _y): A(_y)
{
x = 2;
}
};
class C : public A {
public:
C(int _y) : A(_y)
{
x = 3;
}
};
int main()
{
B b(2);
b.test(); // Test passed
C c(2);
c.test(); // Test not passed
return 0;
}
So an instance of B passes the test if the value of y
is 2
, while an instance of C
passes the test if the value is 3
. However, what I do not like about this implementation is that the value of x
can be changed - even if x
is private, a friend class can still modify it. Ideally, what I would like is to define x
as const
, and as the passing value for B
and C
is known in advance (at compile time), possibly even constexpr
.
My question is as follows:
Is it possible to achieve the behavior above with a const or constexpr value of x
? Can the value of x
be set for each inherited class, but then still tested in the base class?
Upvotes: 0
Views: 487
Reputation: 217810
template seems to help, especially as inheritance seems just here to factorize code:
template <int x>
class A {
public:
int y;
A(int _y): y(_y) {}
void test() {
bool passed = x == y;
std::cout << "Test" << (passed ? "" : " not") << " passed\n";
}
};
// using B = A<2>; // Seems even enough in your example
class B : public A<2> {
public:
using A<2>::A;
};
class C : public A<3> {
public:
using A<3>::A;
};
Upvotes: 2