Hi ppl,
I am trying to run the following code but getting error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
template <typename T>
class Base {
public :
static T& Get() {
static T t;
return t;
}
};
class Derived : public Base<Derived> {
private :
Derived() {}
};
int main() {
Derived& d = Derived::Get();
return 0;
}
|
prog.cpp: In instantiation of ‘static T& Base<T>::Get() [with T = Derived]’:
prog.cpp:18:24: required from here
prog.cpp:7:14: error: ‘Derived::Derived()’ is private within this context
static T t;
^
prog.cpp:14:4: note: declared private here
Derived() {}
^~~~~~~
|
I have following questions
[1] Derived is publically derived from Base, doesn't it makes Get() a member
function of Derived too ?
[2] If [1] is true, and Get becomes a member function of Derived, then why
it's not able to call the private constructor of Derived.
[3] Assume we have multiple classes to be implemented as Singleton, is there
a way we can do it using templates with something similar to the above
example?
Kindly note that I understand :
1) We can make the above code work by adding following line to the code.
1 2 3 4 5
|
class Derived : public Base<Derived> {
private :
Derived() {}
friend Base<Derived>; // line added to Derived
};
|
2) We can make Get() as "non static virtual function" and override in the
derived classes.
I am not looking for the above mentioned solutions. Though, please let me know if this(these) is(are) the only possible solutions to achieve this kind of design.