类 Python C++ 装饰器
有没有办法像python风格一样在C++中装饰函数或方法?
Are there ways to decorate functions or methods in C++ like in python style?
@decorator
def decorated(self, *args, **kwargs):
pass
以宏为例:
DECORATE(decorator_method)
int decorated(int a, float b = 0)
{
return 0;
}
或
DECORATOR_MACRO
void decorated(mytype& a, mytype2* b)
{
}
有可能吗?
推荐答案
std::function
为我提出的解决方案提供了大部分构建块.
std::function
provides most of the building blocks for my proposed solution.
这是我提出的解决方案.
Here is my proposed solution.
#include <iostream>
#include <functional>
//-------------------------------
// BEGIN decorator implementation
//-------------------------------
template <class> struct Decorator;
template <class R, class... Args>
struct Decorator<R(Args ...)>
{
Decorator(std::function<R(Args ...)> f) : f_(f) {}
R operator()(Args ... args)
{
std::cout << "Calling the decorated function.
";
return f_(args...);
}
std::function<R(Args ...)> f_;
};
template<class R, class... Args>
Decorator<R(Args...)> makeDecorator(R (*f)(Args ...))
{
return Decorator<R(Args...)>(std::function<R(Args...)>(f));
}
//-------------------------------
// END decorator implementation
//-------------------------------
//-------------------------------
// Sample functions to decorate.
//-------------------------------
// Proposed solution doesn't work with default values.
// int decorated1(int a, float b = 0)
int decorated1(int a, float b)
{
std::cout << "a = " << a << ", b = " << b << std::endl;
return 0;
}
void decorated2(int a)
{
std::cout << "a = " << a << std::endl;
}
int main()
{
auto method1 = makeDecorator(decorated1);
method1(10, 30.3);
auto method2 = makeDecorator(decorated2);
method2(10);
}
输出:
Calling the decorated function.
a = 10, b = 30.3
Calling the decorated function.
a = 10
附言
Decorator
提供了一个地方,您可以在其中添加函数调用之外的功能.如果你想简单地传递到 std::function
,你可以使用:
Decorator
provides a place where you can add functionality beyond making the function call. If you want a simple pass through to std::function
, you can use:
template<class R, class... Args >
std::function<R(Args...)> makeDecorator(R (*f)(Args ...))
{
return std::function<R(Args...)>(f);
}
相关文章