【发布时间】:2020-04-18 19:06:02
【问题描述】:
有没有使用 lambda 语法定义递归 constexpr 函数的便捷方法?我发现了一种不方便的方法,方法是分配给constexpr 函数指针,但我想要一种减少输入且不更改 lambda 类型的方法。
以普通方式创建递归 constexpr 函数非常简单。 特别是,从 C++11 开始支持使用可能包含三元运算符的单个表达式。
constexpr double factorial2(double x) {
return (x < 0) ? 0 : \
(x == 0) ? 1 : \
/*otherwise*/ (x * factorial2(-1 + x));
}
不太清楚如何使用 lambda 语法来做到这一点。我将在下面包括我的各种失败尝试,但我找到了一种方法来创建一个 constexpr 函数,方法是使用 constexpr 函数指针而不是 auto 作为我用我的 lambda 初始化的变量的类型注释。
typedef double (* factorial_t)(double);
constexpr factorial_t factorial = [](double x) constexpr noexcept -> double {
return (x < 0) ? 0 : \
(x == 0) ? 1 : \
/*otherwise*/ (x * factorial(-1 + x));
};
Clang 会接受这一点,godbolt 上的 GCC 9.2 也会接受。
// foo.cpp
#include <cstdio>
typedef double (* factorial_t)(double);
constexpr factorial_t factorial = [](double x) constexpr noexcept -> double {
return (x < 0) ? 0 : \
(x == 0) ? 1 : \
/*otherwise*/ (x * factorial(-1 + x));
};
int main() {
constexpr auto x{factorial(27)};
printf("%f\n", x);
}
并运行它:
$ rm -f ./a.out && clang++-7 -std=c++17 foo.cpp && ./a.out
10888869450418351940239884288.000000
本节只是一个附录,解释了为什么我决定使用函数指针而不是其他东西。
尝试通过 lambda 生成递归 constexpr 函数失败。
1) 使用auto
正如in this somewhat old question 所解释的,允许使用您在 lambda 中定义的事物的名称,但不能与类型推断很好地交互。使用std::function建议的答案
auto factorial = [](double x) constexpr noexcept -> double {
return (x < 0) ? 0 : \
(x == 0) ? 1 : \
/*otherwise*/ (x * factorial(-1 + x));
};
错误:
bar.cpp:7:31: error: variable 'factorial' declared with deduced type 'auto' cannot appear in its own initializer
/*otherwise*/ (x * factorial(-1 + x));
2) 使用std::function。
这不起作用,因为 std::function 是非文字类型。显然。
// bar.cpp
#include <cstdio>
#include <functional>
constexpr std::function<double(double)> factorial = [](double x) constexpr noexcept -> double {
return (x < 0) ? 0 : \
(x == 0) ? 1 : \
/*otherwise*/ (x * factorial(-1 + x));
};
int main() {
constexpr auto x{factorial(27)};
printf("%f\n", x);
}
失败并显示错误消息:
bar.cpp:5:41: error: constexpr variable cannot have non-literal type 'const std::function<double (double)>'
constexpr std::function<double(double)> factorial = [](double x) constexpr noexcept -> double {
^
/usr/bin/../lib/gcc/aarch64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/functional:1834:11: note: 'function<double (double)>' is
not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
class function<_Res(_ArgTypes...)>
【问题讨论】:
-
这看起来很有希望:stackoverflow.com/a/40873505/2752075
-
@HolyBlackCat:肮脏的把戏......它会在 constexpr 上下文中工作吗?
-
@einpoklum 我不明白为什么它不会,但我没有尝试过。