I am developing the following class, that inherits a template class.
template<typename T>
class test : public T
{
public:
void init() {
T::init();
abc = true;
}
private:
bool abc;
}
On one of my base class I have the following singleton method:
class foo : protected bar
{
public:
static foo &getInstance();
void init();
private:
foo();
foo(foo const&);
void operator=(foo const&);
~foo() {};
}
When I create the following instance:
test<foo> &instance = test<foo>::getInstance();
I get an error:
invalid initialization of reference of type test<foo>& from expression of type foo
Do you know what is happening?
Thanks
test<foo>::getInstance()
resolves to foo::getInstance()
. That function returns a foo&
, not a test<foo>&
. A foo&
cannot be converted to test<foo>&
. Hence the compiler error.
Use
foo& instance = test<foo>::getInstance();
If you must have a test<foo>&
, you need to implement getInstance()
in test
.
template<typename T>
class test : public T
{
public:
void init() {
T::init();
abc = true;
}
static test& getInstance()
{
static test instance;
return instance;
}
private:
bool abc;
};
But then, you'll have to take care of the cascading effects. You'll have to make sure that the constructors and destructors of foo
are declared as either public
or protected
. They cannot be private
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.