【发布时间】:2018-08-27 22:48:09
【问题描述】:
所以情况是这样的:我有两个通过 CRTP 进行静态继承的类。基类有一个 run 方法,该方法使用可变参数模板调用派生方法,以便参数灵活。现在派生类包含一个函数对象。派生类具有基类调用的实现。这似乎没有必要,但在此代码的完整版本中,运行的命令不仅仅是包含的函数。接下来有一个方法通过将所有可变参数和实例绑定到方法CrtpBase::Run 将函数转换为bool(void) 函数。这是我遇到问题的地方。我尝试了两种不同的方法,使用 lambda 的版本被注释掉了。两种方法都不起作用。我的目标是让VoidFunction 绑定所有参数,以便我可以在闲暇时执行该函数而无需参数。我在这里做错了什么?
#include <functional>
#include <utility>
template <typename D>
struct CrtpBase {
template <typename ... Args>
bool Run(Args&& ... args) const {
return static_cast<D&>(*this).Impl(std::forward<Args>(args) ...);
}
};
template <typename ... Args>
struct CrtpDerived : public CrtpBase<CrtpDerived<Args ...>> {
CrtpDerived(std::function<bool(Args ...)> function) : runable(std::move(function)) {}
bool Impl(Args&& ... args) const {
return this->runable(std::forward<Args>(args) ...);
}
std::function<bool(Args ...)> runable;
};
template <typename D, typename ... Args>
std::function<bool()> VoidFunction(CrtpBase<D> base, Args&& ... args) {
// return [&base, &args ...]()->bool{return CrtpBase<D>::template Run<Args ...>(base);};
return std::bind(CrtpBase<D>::template Run<Args ...>, base, std::forward<Args>(args) ...);
}
int main(int argc, char** argv) {
std::function<bool(int&)> fn = [](int& a)->bool{a /= 2; return (a % 2) == 1;};
CrtpDerived<int&> derived(fn);
int x = 7;
auto voided = VoidFunction(derived, x);
bool out = voided();
if ((x == 3) and (out == true)) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
编辑:
- 修复了最终测试中的拼写错误
(out == false)变为(out == true)
【问题讨论】:
标签: c++ variadic-templates crtp