0

I got a piece of code like this.

#define MAKE_SINGLETON_1(classname, traits) \ ; \ protected: \ friend class base::Singleton<classname, traits>; \ private: \ classname(const classname&) = delete; \ classname& operator=(const classname) = delete; \ protected: \ classname(); \ virtual ~classname(); #define MAKE_SINGLETON_2(classname) \ ; \ protected: \ friend class base::Singleton<classname>; \ private: \ classname(const classname&) = delete; \ classname& operator=(const classname) = delete; \ protected: \ classname(); \ virtual ~classname(); // selector #define MAKE_SINGLETON_X(x, A, B, FUNC, ...) FUNC // default parameter #define MAKE_SINGLETON(...) \ MAKE_SINGLETON_X(, ##__VA_ARGS__, MAKE_SINGLETON_1(__VA_ARGS__), MAKE_SINGLETON_2 (__VA_ARGS__)) } 

In other classes, it is used like this

class CConnManager: public Singleton<CConnManager, Mutex> { MAKE_SINGLETON( CConnManager, Mutex ) //other logic } 

I don't understand what MAKE_SINGLETON finally produces. Is it MAKE_SINGLETON_2 that finally called? Could anybody help me explain? Thank you very much.

6
  • Ah, that's a trick to overload macros based on their argument count! It will expand to MAKE_SINGLETON_1 since that's the one with two arguments. Commented Apr 21, 2024 at 2:16
  • @Violet I don't understand the //selector logic. Why FUNC is one of the param then it is also the token? Commented Apr 21, 2024 at 2:38
  • FUNC is just the name of the argument there. MAKE_SINGLETON_X expands to whatever its fourth argument is. The fourth argument will either be MAKE_SINGLETON_1(__VA_ARGS__) or MAKE_SINGLETON_2 (__VA_ARGS__) depending on how many arguments __VA_ARGS__ resolves to. So if you had two arguments, it would shift the rest of the arguments by one. Commented Apr 21, 2024 at 2:46
  • @Violet thank you for your answer. One last question, could you please explain the ## in MAKE_SINGLETON_X? I still don't understand the difference between ____VA_ARGS____ and ##__VA_ARGS__ Commented Apr 21, 2024 at 3:08
  • 1
    So this makes it easier to declare lots of singletons. There ought to be a law against that. :-) Commented Apr 21, 2024 at 8:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.