C++ Factory of templated sigleton - c++

Here a simple project in C++ with 2 design pattern: singleton and factory, sigleton is a templated class too and an interface (IHash) and a class (Hash1).
A simple factory class (HashFactory) creates a sigleton (Hash1); Hash1 inherits the interface IHash and ideally i've Hash1, Hash2 .. HashN.
In compile time i've an error, what's the problem?
g++ main.cpp
main.cpp: In static member function ‘static IHash* HashFactory::get(int)’:
main.cpp:11:15: error: ‘static T& Singleton<T>::getInstance() [with T = Hash1]’ is inaccessible
static T &getInstance() {
^
main.cpp:76:50: error: within this context
if (type == 1)return &Hash1::getInstance();
^
Cut and paste this code to compile it:
#include <iostream>
using namespace std;
///////////////////////////////////////////////
//Class Singleton
template<class T>
class Singleton {
public:
static T &getInstance() {
if (!_instanceSingleton) {
_instanceSingleton = new T();
}
return *_instanceSingleton;
}
private:
static T *_instanceSingleton;
};
template<class T> T *Singleton<T>::_instanceSingleton = 0;
/////////////////////////////////////////////////
//Interface IHash
class IHash {
public:
void function1() {
cout << "function1";
}
virtual void recordHash(bool b) = 0;
~IHash() {
dispose();
}
private:
void dispose() {
cout << "dispose\n";
}
};
///////////////////////////////////////////////////
//Class Hash1 is a singleton and inherits IHash
class Hash1 : public IHash, Singleton<Hash1> {
friend class Singleton<Hash1>;
public:
void recordHash(bool b);
private:
//private constructor, is a sigleton
Hash1();
};
Hash1::Hash1() {
cout << "create Hash1\n";
}
void Hash1::recordHash(bool b) {
cout << b << " recordHash\n";
}
////////////////////////////////////////////////////
//Factory for IHash
class HashFactory {
public:
static IHash *get(int type) {
if (type == 1)return &Hash1::getInstance();
// if (type == 2)return &Hash2::getInstance();
// if (type == 3)return &Hash3::getInstance();
return 0;
}
};
//////////////////////////////////////////////////////
int main() {
int type=1;
IHash *a = HashFactory::get(type);
a->recordHash(true);
a->function1();
return 0;
}

Hash1's inheritance from Singleton<Hash1> is implicitly private. Change that to
class Hash1 : public IHash, public Singleton<Hash1> {

Related

Accessing Inherited Functions

In multiple inheritance,where all the base class contains same function name with different functionality, we can access the protected function from particular base class using "::" scope resolution operator.
However, I tried something else. I created the objects of the base class in inside the child class. And tried calling the function using through object of that particular class.
But I was getting the following compiler error:
"‘void A::func(int&)’ is protected within this context."
Please let me know where did i go wrong.
#include <iostream>
using namespace std;
class A
{
protected:
void func(int & a)
{
a = a * 2;
}
};
class B
{
protected:
void func(int & a)
{
a = a * 3;
}
};
class C
{
protected:
void func(int & a)
{
a = a * 5;
}
};
class D : public A,public B,public C {
public:
int a;
A a_val;
B b_val;
C c_val;
void update_val(int new_val)
{
a = new_val;
a_val.func(a);
b_val.func(a);
c_val.func(a);
}
void check(int);
};
void D::check(int new_val)
{
update_val(new_val);
cout << "Value = " << a << endl;
};
int main()
{
D d;
int new_val;
cin >> new_val;
d.check(new_val);
}
If you want to keep your code with the base classes as having independent functionality and still remaining protected the easiest way to resolve your issue is by slightly changing the name of your protected functions and adding a public function that calls the protected members: See these class declarations for example:
class A {
public:
void func( int& a ) {
func_impl( a );
}
protected:
void func_impl( int& a ) {
a = a * 2;
}
};
class B {
public:
void func( int& b ) {
func_impl( b );
}
protected:
void func_impl( int& b ) {
b = b * 3;
}
};
class C {
public:
void func( int& c ) {
func_impl( c );
}
protected:
void func_impl( int& c ) {
c = c * 5;
}
};
class D : public A, public B, public C {
public:
int a;
A a_val;
B b_val;
C c_val;
void update_val( int val ) {
a = val;
a_val.func( a );
b_val.func( a );
c_val.func( a );
}
void check( int );
};
void D::check( int val ) {
update_val( val );
std::cout << "Value = " << a << std::endl;
}
This provides a nice public interface to call the protected member functions. This also resolves the issue of accessing the protected members. When I run your program and input a value of 5 it returns a result of 150 and works as expected.
This snippet should show you how inheritance works and when you can and can not access protected members:
class DerivedA : public Base {
public:
Base b;
void call_message() {
b.message(); // Protected Member of Base class can not be accessed
}
};
class DerivedB : public Base {
public:
void call_message() {
message(); // This works without problem!
}
};
Just as I did above one way to resolve this is by adding a public interface caller to the protected implementation.
class Base {
public:
void message() {
message_impl();
}
protected:
void message_impl() {
std::cout << "This is a protected member of Base\n";
}
};
Now you can do this:
class DerivedA {
public:
Base b;
void call_message() {
b.message(); // Accessible through public interface.
}
};
When you are in your derived class, it has access to its own ancestor methods. But it doesn't have access to your variables member protected and private methods and variables.
Redesign your code, you are trying things and contorting the other classes design for bad reasons. Francis' code is a good solution, but D doesn't need to inherit from anything.
If you don't want to create another function, you can do something like this:
#include <iostream>
using namespace std;
class A
{
protected:
void func(int & a)
{
a = a * 2;
}
};
class B
{
protected:
void func(int & a)
{
a = a * 3;
}
};
class C
{
protected:
void func(int & a)
{
a = a * 5;
}
};
class D : public A,public B,public C {
public:
int a;
void update_val(int new_val)
{
a = new_val;
this->A::func(a);
this->B::func(a);
this->C::func(a);
}
void check(int);
};
void D::check(int new_val)
{
update_val(new_val);
cout << "Value = " << a << endl;
};
int main()
{
D d;
int new_val;
cin >> new_val;
d.check(new_val);
}
This works because, this refers to the current instance of class D, and it already inherits class A, class B, class C. So you can directly access the protected functions of the respective classes.
Remember: It will not work if you have not inherited the classes.

Is that possible to know all the name of derived classes?

Suppose we have a base class and a bunch of derived classes. Is there any way or mechanism to know all the derived class names programmatically?
Maybe reflection is a good idea, but it's not available on C++. I suppose there will be some kind of template that can finish this job during compilation.
class Base{
public:
virtual void print(){
// This function should print all the names of derived class.
}
virtual Base* getInstance(string class_name){
// This function should return an instance related to the class name.
}
};
class Derived_1 : public Base{ // Suppose we have 100 Derived_X classes,
// so we don't want to add its name to a list manually.
};
int main(){
Base base;
base.print(); // This should print the name of all the derived class.
base.getInstance("Derived_1"); // This should return an instance of Derived_1
return 0;
}
This solution is based on the fact that it seems you are actually looking for a factory. It uses a small macro to ease classes registration, hope you don't care about it.
factory.h
#ifndef __FACTORY_H__
#define __FACTORY_H__
#include <map>
#include <functional>
#include <string>
#include <iostream>
template<class B>
class Factory {
std::map<std::string, std::function<B*()>> s_creators;
public:
static Factory<B>& getInstance() {
static Factory<B> s_instance;
return s_instance;
}
template<class T>
void registerClass(const std::string& name) {
s_creators.insert({name, []() -> B* { return new T(); }});
}
B* create(const std::string& name) {
const auto it = s_creators.find(name);
if (it == s_creators.end()) return nullptr; // not a derived class
return (it->second)();
}
void printRegisteredClasses() {
for (const auto &creator : s_creators) {
std::cout << creator.first << '\n';
}
}
};
#define FACTORY(Class) Factory<Class>::getInstance()
template<class B, class T>
class Creator {
public:
explicit Creator(const std::string& name) {
FACTORY(B).registerClass<T>(name);
}
};
#define REGISTER(base_class, derived_class) \
Creator<base_class, derived_class> s_##derived_class##Creator(#derived_class);
#endif
example.cpp
#include "factory.h"
#include <memory>
class Base {
public:
virtual void printName() const { std::cout << "Base\n"; }
};
class Derived1 : public Base {
public:
virtual void printName() const override { std::cout << "Derived1\n"; }
};
REGISTER(Base, Derived1);
class Derived2 : public Base {
public:
virtual void printName() const override { std::cout << "Derived2\n"; }
};
REGISTER(Base, Derived2);
int main() {
std::cout << "Registered classes:" << std::endl;
FACTORY(Base).printRegisteredClasses();
std::cout << "---" << std::endl;
std::unique_ptr<Base> derived1(FACTORY(Base).create("Derived1"));
derived1->printName();
return 0;
}
Note: requires C++11.
For the getInstance you can declare it a template (needs C++14). To get all the names of the derived classes in the program you probably have to resort to some preprocessor hack.
#include <type_traits>
class Base
{
public:
virtual ~Base () = default;
template < typename T,
typename = std::enable_if_t<std::is_base_of<Base, T>::value, void>
>
T getInstance() { return T{}; }
};
class Derived : public Base {};
class NotDerived {};
int main(){
Base base;
base.getInstance<Derived>();
// error: no matching member function for call to 'getInstance'
//base.getInstance<NotDerived>();
}
Regarding the name of the derived classes, I propose a solution based on a BaseList class/struct, with a static std::set (or other container) of names, a template Base class/struct, that inherit from BaseList and whose template parameter is the derived class (CRTP style) and (to semplify the construction of the derived classes/struct, a C-style macro (I know... macros are distilled evil... but sometimes...) to create the declaration of the derived classes/structs with a necessary static method, that declare the name of the derived class/struct, and a member (that activate the registration of the name).
The following is a full example (unfortunately is a C++11 one)
#include <set>
#include <string>
#include <iostream>
struct BaseList
{
static std::set<std::string> const & derList (std::string const & dn)
{
static std::set<std::string> dl;
if ( dn.size() )
dl.insert(dn);
return dl;
}
static void print ()
{
std::cout << "derived names: ";
for ( auto const & dn : derList("") )
std::cout << dn << ", ";
std::cout << std::endl;
}
};
template <typename Der>
struct Base : public BaseList
{
static std::size_t setNameInList ()
{ return derList(Der::name()).size(); }
static std::size_t id;
};
template <typename Der>
std::size_t Base<Der>::id = setNameInList();
#define setDerived(nameDer) \
struct nameDer : public Base<nameDer>\
{ \
std::size_t idc { id }; \
static std::string name () \
{ return #nameDer; }
setDerived(Derived_1)
// other elements
};
setDerived(Derived_2)
// other elements
};
setDerived(Derived_3)
// other elements
};
int main()
{
BaseList::print();
}
Regarding the getInstance() problem, the only solution that I can imagine is the same solution proposed by Enry Menke (+1), so I suggest that you get the instance through a template type parameter.

C++ (sort of) factory

I've seen a number of posts regarding C++ factories, but so far I haven't seen a solution that solves my problem. (Though I may be missing something.)
Example console app:
#include <memory>
#include <map>
#include <iostream>
using namespace std;
class ResourceManager;
/// abstract base class
class Identity
{
public:
int Id() const { return _id; }
/// make this an abstract class
virtual ~Identity() = 0 {}
protected:
Identity() { _id = _nextId++; }
private:
int _id;
static int _nextId;
};
int Identity::_nextId = int();
/// derived classes
class Component : public Identity
{
friend class ResourceManager;
public:
~Component() { }
};
class Entity : public Identity
{
friend class ResourceManager;
public:
~Entity() { }
};
class ResourceManager
{
public:
template<typename T>
T& Create()
{
auto ptr = std::make_shared<T>();
auto id = ptr->Id();
_resources[id] = std::move(ptr);
return *dynamic_pointer_cast<T>(_resources[id]);
}
private:
std::map<int, std::shared_ptr<Identity>> _resources;
};
int main(int argc, char *argv[])
{
cout << "Factory test" << endl;
ResourceManager r;
auto& e = r.Create<Entity>();
cout << "e.id = " << e.Id() << endl;
Entity e2;
cout << "e2.id = " << e2.Id() << endl;
Component c;
cout << "c.id = " << c.Id() << endl;
std::getchar();
}
I need to make sure that only ResourceManager can instantiate Entity, Component and any classes that derive from them.
I've looked and adding ResourceManager as a friend class to Identity, and making the constructors private or protected, with no success. (This could be a blind alley, or just an implementation problem on my end.)
Any suggestions?
Update and Edit
Replaced code with compilable example. Although the constructor for Identity() is protected, I can still directly instantiate derived classes.
Following should work:
friend class ResourceManager; should be in each derivated classes.
(friend is not inherited).
class ResourceManager;
/// abstract base class
class Identity
{
public:
int Id() const { return _id; }
/// make this an abstract class
virtual ~Identity() = 0;
// Forbid any copy
Identity(const Identity&) = delete;
Identity(const Identity&&) = delete;
Identity& operator = (const Identity&) = delete;
Identity& operator = (Identity&&) = delete;
protected:
Identity() { _id = _nextId++; }
private:
int _id;
static int _nextId;
};
// empty destructor
Identity::~Identity() {}
int Identity::_nextId = 0;
/// derived classes
class Component : public Identity
{
friend class ResourceManager;
public:
~Component() { }
protected:
Component() = default;
};
class Entity : public Identity
{
friend class ResourceManager;
public:
~Entity() { }
protected:
Entity() = default;
};
class ResourceManager
{
public:
template<typename T>
T& Create()
{
std::unique_ptr<T> ptr(new T);
T& res = *ptr;
_resources[ptr->Id()] = std::move(ptr);
return res;
}
/// TODO: need to make sure that resource ID is actually of type T
/// and that _resources contains ID.
template<typename T>
T* Get(int id)
{
auto it = _resources.find(id);
if (it == _resources.end()) {
return nullptr;
}
return dynamic_cast<T*>(it->second.get());
}
private:
std::map<int, std::unique_ptr<Identity>> _resources;
};
Note that since ResourceManager owns the resource I change std::shared_ptr to std::unique_ptr.
I fixed ResourceManager::Get with invalid id.
Have you tried a protected construtor?
class Identity
{
friend class ResourceManager;
public:
int Id() { return _id; }
virtual ~Identity() = 0;
protected:
Identity() {
_id = _nextId++;
}
private:
static int _nextId;
// do not forget to put "int Identity::_nextId = 0;" in a source file
};
Identity::~Identity()
{
}
But you need to repeat this pattern in every derived class. Thus making ResourceManager a friend and making the constructor private or protected.

Recursive Template idiom how to avoid that the base class is friend of the child classes

I use the recursive template idiom to automatically register all children of a base class in a factory. However in my design the child class must have as a friend class the base class. As the Constructor of my Base class should be private to avoid instantiation of this class other than via the factory.
The overal aim would be that the registration of the factory is done in the BaseSolver and the ChildClasses cannot be instantiated other than via the factory.
Here is the code of my base class which automatically registers all children in the SolverFactory.
template<class T>
struct BaseSolver: AbstractSolver
{
protected:
BaseSolver()
{
reg=reg;//force specialization
}
virtual ~BaseSolver(){}
/**
* create Static constructor.
*/
static AbstractSolver* create()
{
return new T;
}
static bool reg;
/**
* init Registers the class in the Solver Factory
*/
static bool init()
{
SolverFactory::instance().registerType(T::name, BaseSolver::create);
return true;
}
};
template<class T>
bool BaseSolver<T>::reg = BaseSolver<T>::init();
And here the header file of my child class:
class SolverD2Q5 : public BaseSolver<SolverD2Q5>{
private:
//how can I avoid this?
friend class BaseSolver;
SolverD2Q5();
static const std::string name;
}
This works fine. However I really do not like to have to add the BaseSolver as a friend class, however I do not want the constructor and the static member name to be public.
Is there a more elegant solution or a better layout to avoid this?
UPDATE:
I believe the trick has not been understood hence I created the complete solution now. It is just one little change to the code of the OP. Just replace T in the BaseSolver with an empty class definition deriving from T.
Original Text:
I think you can do it by delegating the friendship to a wrapper class that is private to the base Solver. This class will inherit from any class for which instances are to be created. The compiler should optimize the wrapper class away.
#include <iostream>
#include <map>
struct AbstractSolver { virtual double solve() = 0; };
class SolverFactory
{
std::map<char const * const, AbstractSolver * (*)()> creators;
std::map<char const * const, AbstractSolver *> solvers;
public:
static SolverFactory & instance()
{
static SolverFactory x;
return x;
}
void registerType(char const * const name, AbstractSolver *(*create)())
{
creators[name] = create;
}
AbstractSolver * getSolver(char const * const name)
{
auto x = solvers.find(name);
if (x == solvers.end())
{
auto solver = creators[name]();
solvers[name] = solver;
return solver;
}
else
{
return x->second;
}
}
};
template<class T> class BaseSolver : public AbstractSolver
{
struct Wrapper : public T { // This wrapper makes the difference
static char const * const get_name() { return T::name; }
};
protected:
static bool reg;
BaseSolver() {
reg = reg;
}
virtual ~BaseSolver() {}
static T * create() {
return new Wrapper; // Instantiating wrapper instead of T
}
static bool init()
{
SolverFactory::instance().registerType(Wrapper::get_name(), (AbstractSolver * (*)())BaseSolver::create);
return true;
}
};
template<class T>
bool BaseSolver<T>::reg = BaseSolver<T>::init();
struct SolverD2Q5 : public BaseSolver<SolverD2Q5>
{
public:
double solve() { return 1.1; }
protected:
SolverD2Q5() {} // replaced private with protected
static char const * const name;
};
char const * const SolverD2Q5::name = "SolverD2Q5";
struct SolverX : public BaseSolver<SolverX>
{
public:
double solve() { return 2.2; }
protected:
SolverX() {} // replaced private with protected
static char const * const name;
};
char const * const SolverX::name = "SolverX";
int main()
{
std::cout << SolverFactory::instance().getSolver("SolverD2Q5")->solve() << std::endl;
std::cout << SolverFactory::instance().getSolver("SolverX")->solve() << std::endl;
std::cout << SolverFactory::instance().getSolver("SolverD2Q5")->solve() << std::endl;
std::cout << SolverFactory::instance().getSolver("SolverX")->solve() << std::endl;
char x;
std::cin >> x;
return 0;
}

Using the Visitor Pattern with template derived classes

I try to implement the Visitor pattern with templated derived classes
I work with gcc 4.5
here is the VisitorTemplate.hpp, I specialized Derived in the class Visitor, but I'd like to be able to handle any type:
edit : thanks to the suggestions of interjay, the code compiles and runs without errors now
#ifndef VISITORTEMPLATE_HPP_
#define VISITORTEMPLATE_HPP_
#include <iostream>
#include <string>
using namespace std;
template<class T> Derived;
class Visitor
{
public:
virtual void visit(Derived<string> *e) = 0;
};
class Base
{
public:
virtual void accept(class Visitor *v) = 0;
};
template<class T>
Derived: public Base
{
public:
virtual void accept(Visitor *v)
{
v->visit(this);
}
string display(T arg)
{
string s = "This is : " + to_string(arg);
return s;
}
};
class UpVisitor: public Visitor
{
virtual void visit(Derived<string> *e)
{
cout << "do Up on " + e->display("test") << '\n';
}
};
class DownVisitor: public Visitor
{
virtual void visit(Derived<string> *e)
{
cout << "do Down on " + e->display("test") << '\n';
}
};
#endif /* VISITORTEMPLATE_HPP_ */
main.cpp
Base* base = new Derived<string>();
Visitor* up = new UpVisitor();
Visitor* down = new DownVisitor();
base->accept(up);
base->accept(down);
Now my goal is to use Derived in visit without specializing; unfortunately, visit is a virtual method so I can't template it
From Modern C++ - Design Generic Programming and Design Patterns Applied - Andrei Alexandrescu
#include <iostream>
class BaseVisitor
{
public:
virtual ~BaseVisitor() {};
};
template <class T, typename R = int>
class Visitor
{
public:
virtual R visit(T &) = 0;
};
template <typename R = int>
class BaseVisitable
{
public:
typedef R ReturnType;
virtual ~BaseVisitable() {};
virtual ReturnType accept(BaseVisitor & )
{
return ReturnType(0);
}
protected:
template <class T>
static ReturnType acceptVisitor(T &visited, BaseVisitor &visitor)
{
if (Visitor<T> *p = dynamic_cast< Visitor<T> *> (&visitor))
{
return p->visit(visited);
}
return ReturnType(-1);
}
#define VISITABLE() \
virtual ReturnType accept(BaseVisitor &v) \
{ return acceptVisitor(*this, v); }
};
/** example of use */
class Visitable1 : public BaseVisitable<int>
{
/* Visitable accept one BaseVisitor */
public:
VISITABLE();
};
class Visitable2 : public BaseVisitable<int>
{
/* Visitable accept one BaseVisitor */
public:
VISITABLE();
};
class VisitorDerived : public BaseVisitor,
public Visitor<Visitable1, int>,
public Visitor<Visitable2, int>
{
public:
int visit(Visitable1 & c)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int visit(Visitable2 & c)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main(int argc, char **argv)
{
VisitorDerived visitor;
Visitable1 visitable1;
Visitable2 visitable2;
visitable1.accept(visitor);
visitable2.accept(visitor);
}
Is possible to avoid dynamic_cast with CRTP pattern like:
#include <iostream>
class BaseVisitor
{
public:
virtual ~BaseVisitor() {};
};
template <class T>
class Visitor
{
public:
virtual void visit(T &) = 0;
};
template <class Visitable>
class BaseVisitable
{
public:
template <typename T>
void accept(T & visitor)
{
visitor.visit(static_cast<Visitable &>(*this));
}
};
/** example of use */
class Visitable1 : public BaseVisitable<Visitable1>
{
};
class Visitable2 : public BaseVisitable<Visitable2>
{
};
class VisitorDerived : public BaseVisitor,
public Visitor<Visitable1>,
public Visitor<Visitable2>
{
public:
void visit(Visitable1 & c)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void visit(Visitable2 & c)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main(int argc, char **argv)
{
VisitorDerived visitor;
Visitable1 visitable1;
Visitable2 visitable2;
visitable1.accept<VisitorDerived>(visitor);
visitable2.accept<VisitorDerived>(visitor);
}
Your Derived class cannot use Visitor because it hasn't been defined yet (it was only forward declared, and is therefore an incomplete type).
You can fix the compile error by putting the Visitor definition before Derived. You will also need to forward-declare Derived before defining Visitor:
template <class T> class Derived;
class Visitor {
public:
virtual void visit(Derived<string> *e) = 0;
};
template <class T>
class Derived : public Base {
//.... can call Visitor methods here ...
};