lundi 14 mai 2018

How exactly should one use declttype to deduce the return type of a function which returns a class instance instantiated over template

We have a basic function which adds 2 floats(to certain degree of accuracy).

  float add(float x, float y)
  {
  std::cout << "\n in the add function \n";
  float res = x+y;
  std::cout << "\n exiting the add function \n";
  return res;
  }

We have, a forward declaration,

template <typename> struct Logger;

followed by, implementation,

template<typename R, typename... Args>
struct Logger<R(Args...)>
{
    // these  would be members 
  function<R(Args...)> func; 
  string name;

   // this would be ctor 
  Logger(const function<R(Args...)>& func, const string& name)
    :
      func{func},
      name{name}
  {

  }
    // this would be the overload fun operator 
  R  operator() (Args ...args) const 
  {
    cout << "\n Entering Into ... .......\n" << name << endl; 
    R result = func(args...); //  this would be actual call to the basic      function 
    cout << "\n Exiting from  ...  \n" << name << endl; 
    return result; //  this would be of type R, the return from the function call

  }
};

We then have a function,

// This function would provide an instantiation of 
// the Logger class, 
// and that would call the ctor of the Logger class 
template <typename R, typename... Args>
auto make_logger(R (*func)(Args...), const string& name ) 
{
  return Logger<R(Args...)>{

    std::function<R(Args...)>(func),
    name
  };

}
// Notice, there is no decltype in the above function, and I would like to use 
// the decltype, I am aware that decltype cannot be used on packed template argument

// Here is the use of the API, in some main function

auto logger_add = make_logger(add, "**Adding Numbers**");
auto result = logger_add(2.0, 3.0);

Problem:

Can one make the above code work in C++11? Specifically, using declytype, how would one use the make_logger function.

Notes: I am following a book, and the above code is taken from, https://github.com/Apress/design-patterns-in-modern-cpp/blob/master/Structural/Decorator/decorator.cpp

Aucun commentaire:

Enregistrer un commentaire