【发布时间】:2018-05-14 13:58:33
【问题描述】:
我们有一个添加 2 个浮点数的基本函数(达到一定的准确度)。
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;
}
我们有一个前向声明,
template <typename> struct Logger;
紧随其后,实施,
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
}
};
然后我们有一个函数,
// 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
//这里是API的使用,在一些main函数中
auto logger_add = make_logger(add, "**Adding Numbers**");
auto result = logger_add(2.0, 3.0);
问题:
可以使上述代码在 C++11 中工作吗?具体来说,使用declytype,如何使用make_logger函数。
注意事项: 我正在关注一本书,上面的代码取自, https://github.com/Apress/design-patterns-in-modern-cpp/blob/master/Structural/Decorator/decorator.cpp
【问题讨论】:
-
为什么要在这里使用 decltype?你命名你返回的类型。
-
我正在寻找 auto func() -> make_logger 函数的 int 类型语法
-
所以...
auto make_logger() -> Logger<R(Args...)>。老实说,您甚至不需要尾随返回类型。
标签: c++ c++11 templates c++14 decltype