If I have something like
class Base {
static int staticVar;
}
class DerivedA : public Base {}
class DerivedB : public Base {}
Will bot
The sample code given by @einpoklum is not working as it is because of the missing initialization of the static member foo_
, missing inheritance in FooHolder
declaration, and missing public
keywords since we are dealing with classes. Here is the fixed version of it.
#include
#include
class A {
public:
virtual const int& Foo() const = 0;
};
template
class FooHolder : public virtual A {
public:
const int& Foo() const override { return foo_; }
static int foo_;
};
class B : public virtual A, public FooHolder { };
class C : public virtual A, public FooHolder { };
template<>
int FooHolder::foo_(0);
template<>
int FooHolder::foo_(0);
int main()
{
B b;
C c;
std::cout << b.Foo() << std::endl;
std::cout << c.Foo() << std::endl;
}