0

What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this:

C->member_method();

instead of:

Config::inst()->member_method();

but I'm not sure how to go about it. Here is my singleton class:

class Config {
private:
    Config() {}

    static Config* m_instance;

public:
    ~Config() {}

    static Config* inst() {
        if (m_instance == nullptr) {
            m_instance = new Config;
        }
        return m_instance;
    }

    bool load();
};

Thanks in advance

th3v0id
  • 463
  • 3
  • 15
  • You mean just `member_method()`? What's wrong with `Config::instance()->load()`? That's kind of how singletons work. – Barry Jun 14 '15 at 20:13
  • 1
    Looks like you simply want to create a global variable. You don't even need a pointer. You can just declare `Config C;` at the global scope and be using `C.member_method();`. But it doesn't seem like a terribly good idea. – The Paramagnetic Croissant Jun 14 '15 at 20:14
  • Awarded for the most weird design in 2015. – πάντα ῥεῖ Jun 14 '15 at 20:16
  • I was thinking about going the singleton route because I need a global class which contains variables loaded in from a configuration file. From what I've read, there are advantages of using a singleton instead of something like a static object. However, I don't want to call the singleton's methods like `Config::inst()->method_name()` throughout all of my code cus lazy. I guess if there's not a way to do this, I'll just use a static object – th3v0id Jun 14 '15 at 20:21
  • Once you go the singleton way there is no coming back. Your avatar confirm your allegiance to the dark side. – UmNyobe Jun 14 '15 at 20:23
  • That class doesnt have to be a singleton. Create a normal class with non static method, create a static instance of the class and voila – UmNyobe Jun 14 '15 at 20:25
  • @UmNyobe Doesn't necessarily have to be a `static` instance. – πάντα ῥεῖ Jun 14 '15 at 20:32

2 Answers2

1

Use a static class method for a facade, to let you use your preferred syntax:

class Config {

    // The declarations you already have, then:

public:

    static void member_method()
    {
        inst()->member_method_impl();
    }
private:
    void member_method_impl();
};

Then, simply invoke:

Config::member_method();

If you just want to use a class pointer-like syntax, you don't need to declare anything. Just use:

auto C=Config::inst();

then:

C->member_method();
Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106
1

Simply create a normal class without static methods, ditch the singleton pattern aside, and create an instance.

The burden of singleton pattern usually outweigh any benefit.

Community
  • 1
  • 1
UmNyobe
  • 21,341
  • 8
  • 52
  • 85
  • I think im going to follow your advice. I don't fully understand the singleton pattern and what I need is fairly straight forward / simple. – th3v0id Jun 14 '15 at 20:36