Application of policy-based design

I did not read the book Modern C ++ Design, but I found the idea of ​​introducing behavior through interesting patterns. I'm trying to apply it myself.

I have a class that has a journal that I thought could be introduced as a policy. The logger has a log () method that accepts std :: string or std :: wstring depending on its policy:

// basic_logger.hpp
template<class String>
class basic_logger
{
public:
    typedef String string_type;

    void log(const string_type & s) { ... }
};
typedef basic_logger<std::string> logger;
typedef basic_logger<std::wstring> wlogger;

// reader.hpp
template<class Logger = logger>
class reader
{
public:
    typedef Logger logger_type;

    void read()
    {
        _logger.log("Reading...");
    }

private:
    logger_type _logger;
};

Currently, the quest is whether the reader should take Logger as an argument, for example, above, or take String, and then create an instance of basic_logger as an instance variable? For instance:

template<class String>
class reader
{
public:
    typedef String string_type;
    typedef basic_logger<string_type> logger_type;

    // ...

private:
    logger_type _logger;
};

What is the right way?

+3
source share
3 answers

, . char_traits basic_string, , M++ D, ( , , M++ D). - :

template<class String, class Logger=basic_logger<String> >
struct reader : Logger {
  void read() {
    this->log("Reading...");
  }
};
+2

, , ? , , - .

IMHO , String, Logger . , - logger - , , .

+1

, .

, , , , ... , .

, Loki::Singleton, .

template
<
  typename T,
  template <class> class CreationPolicy = CreateUsingNew,
  template <class> class LifetimePolicy = DefaultLifetime,
  template <class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
  class MutexPolicy = LOKI_DEFAULT_MUTEX
>
class SingletonHolder;

, ?

- , , .

Well, now I have to admit that I'm not quite sure that I need a class with a given number of template parameters, personally, I would prefer something:

template
<
  class T,
  class CreationPolicy = CreateUsingNew<T>,
  class LifetimePolicy = DefaultLifeTime<T>,
  class MutexPolicy = LOKI_DEFAULT_MUTEX,
  template <class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL
>
class SingletonHolder;

The latter cannot help; you must pass it to the class itself SingletonHolder.

However, it’s easier for me to exchange policies here, this allows me to define policies such as:

template <class T, size_t Param> MyCreationPolicy;

And use directly, without wrapping it for the given parameter value, so that it matches the signature.

+1
source

Source: https://habr.com/ru/post/1739782/


All Articles