【发布时间】:2021-01-09 02:56:13
【问题描述】:
不幸的是,这个问题的完整背景太复杂而无法解释,但我只想说它涉及一些复杂的模板元编程,我发现自己不得不做一些有趣的事情。我试图将我遇到的一个问题归结为一个最小的例子,所以这个问题可能看起来很尴尬。如果可以做到这一点,我很想知道如何做,如果没有,我很想听听可能的替代方案。
我想创建一个函数,该函数将 lambda 函数作为输入,该函数可能返回 void 或其他内容。如果它确实返回void,我想将它转换成一个相同的lambda,而不是返回void,而是返回true。
template <typename InputFuncType>
auto function_converter(InputFuncType lambda_func)
{
// I also need to figure out how to deduce the return type of lambda_func
// might be something like this.
if constexpr (std::is_same<std::result_of<InputFuncType>::type, void>::value)
{
// Current best guess. Note that in the context of the converter, I don't explicitly know
// lambda_func's input type, so I'm not sure how to do something like this.
return [](InputFuncType::input_args_t... args) {lambda_func(args); return true;};
}
return lambda_func;
}
// target usage
const auto lam1 = [](int a) {return;};
const auto lam2 = function_converter(lam1);
int x = 4;
lam1(x); // returns void
const bool y2 = lam2(x); // returns true
我使用的是 c++17。
【问题讨论】:
-
如果输入的返回值不是
void,你期望它返回什么?另外,您是否关心该解决方案是否对 SFINAE 友好? -
如果返回类型 != void,则返回类型不变。 SFINAE:老实说,不确定。我对它隐约熟悉,但不足以知道您的问题的答案。
标签: c++ templates c++17 template-meta-programming generic-lambda