-2

I have template class Application

It should be something like singleton, I want to create it once, and get from other files.

//main.cpp
Application<NetworkService, User, Policy> a;
a.run();
//other files
//instead of auto a = Application::getInstance<NetworkService, User, Policy>() I want just
auto a = Application::getInstance()

Is it possible? Maybe in another form, I just don't want to use template specification to access to created early global Application object

Mike Kinghan
  • 46,463
  • 8
  • 124
  • 156
Sergey Kolesov
  • 480
  • 4
  • 15
  • 1
    `using NetworkServiceApp = Application; ... NetworkServiceApp a; ...` Is that what you meant? Make it so you don't have to repeat the template parameters everywhere you mention the type? – doug65536 May 30 '16 at 13:46
  • Application is a part of a hpp library. Application withtemplate specification should be created in main.cpp and than users should access to the created instance using my library function without template arguments. And in my library I don't know what template arguments were used. – Sergey Kolesov May 30 '16 at 14:03

1 Answers1

0

Add a class ApplicationBase, and have Application inherit from it. Put the singleton accessor in the base class, and add virtual functions for everything you want to call.

This way you will always interact with the base class, but you can use template args to construct it in main.cpp.

class ApplicationBase {
public:
    static ApplicationBase* getInstance() {
        return m_instance;
    }

    virtual void foo() = 0;

protected:
    static ApplicationBase* m_instance;
}

template<TNetworkService, TUser, TPolicy>
class Application : public ApplicationBase {
public:
    Application () {
        m_instance = this;
    }

    virtual void foo() {
        // do something
    }
}

Then outside main you can call

auto a = ApplicationBase::getInstance();
a->foo();

The constructor for Application will have to register the singleton in the parent class.

Joey Yandle
  • 141
  • 4