用于处理方法结果的变分模板
Variadic template for processing method result
假设我有一个类有一些方法:
class Foo {
bool someMethodA(int someParamA, double someParamB, int someParamC);
bool someMethodB(double someParamA);
bool someMethodC(double someParamA);
...
}
每个方法都有不同的签名。有没有一种方便的方法可以调用这些方法,以便在true(成功(时调用通知程序方法?
notifySuccess();
执行此操作的宏是:
// Call a function notifyAll() on success
#define NOTIFY_ON_SUCCESS(func)
bool success = func;
if (success) {
notifySuccess();
}
return success;
有人建议有一种方法可以使用可变模板来实现这一点?类似于:
template <typename... ARGS>
bool CallImplAndNotify(bool (&SceneImpl::*func)(ARGS...), ARGS... args) {
bool result = func(args...);
...
}
模板需要稍微充实一下,但您走在了正确的轨道上:
#include <type_traits>
#include <functional>
#include <iostream>
void notifySuccess()
{
std::cout << "Success" << std::endl;
}
template <typename Obj, typename... ARGS,
typename ...Params>
bool CallImplAndNotify(Obj &obj, bool (Obj::*func)(ARGS...),
Params && ...params)
{
if ((obj.*func)(std::forward<Params>(params)...))
{
notifySuccess();
return true;
}
return false;
}
class Foo {
public:
bool someMethodA(int someParamA, double someParamB, int someParamC)
{
return true;
}
bool someMethodB(double someParamA)
{
return false;
}
bool someMethodC(double someParamA)
{
return true;
}
};
int main()
{
Foo f;
CallImplAndNotify(f, &Foo::someMethodA, 0, 1.0, 2.0);
CallImplAndNotify(f, &Foo::someMethodB, 1.0);
CallImplAndNotify(f, &Foo::someMethodC, 1.0);
return 0;
}
似乎一个简单的函数就可以做到这一点:
bool NotifyOnSuccess(bool b) {
if (b) {
notifySuccess();
}
return b;
}
并称之为
NotifyOnSuccess(foo.someMethodA(42, 5.1, 69));
NotifyOnSuccess(foo.someMethodB(5.1));
template <class... Args, class...Ts>
bool CallImplAndNotify(bool (&SceneImpl::*func)(Args...), Ts&&... ts) {
bool result = (this->*func)(std::forward<Ts>(ts)...);
if(result) notify_on_success();
return result;
}
或者:
template<class T>struct tag_t{using type=T;};
template<class T>using block_deduction=typename tag_t<T>::type;
template <class... Args>
bool CallImplAndNotify(bool (&SceneImpl::*func)(Args...), block_deduction<Args>... args) {
bool result = (this->*func)(std::forward<Args>(args)...);
if(result) notify_on_success();
return result;
}
第一种可能稍微更高效,第二种允许{}
式构造并传递NULL
令牌而不是nullptr
。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- Visual C++: MSVC vs. GCC+CLANG: 处理 lambda 捕获类成员变量,正确的方法是什么?
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 处理编译器关于可能丢失数据的警告的最优雅方法是什么
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 是否有可以处理方法调用依赖关系的设计模式?
- 将不同类型的多种参数发送到处理方法的最佳方法.C
- C 最常见的并行处理方法.pthreads
- 不同处理方法的设计模式,这些方法共享一些常见的处理链
- C++良好的错误处理方法
- C/CPP 宏或预处理器,用于处理方法的多个版本
- 为什么这个简单的批处理方法不能按预期工作?
- 首选的错误处理方法
- erase删除迭代器所指向的元素失败时的处理方法
- 用于处理方法结果的变分模板