如何限制我的模板仅接受具有特定输入和参数的 lambda输出类型?
受到计算函数泰勒级数的其他问题的启发(原始问题),我编写了一个模板没有任何限制来成功计算总和。这是当前代码(模板主体已删除,正如 @Elliott 所说,这与要点无关..)
#include <iostream>
#include <cmath>
#include <limits>
template<typename ftn>
long double Taylor_sum(ftn terms_to_sum) { /* Summation calculation goes here... */ return result; };
int main(){
using namespace std; long double x; cin >> x ;
long double series_sum = Taylor_sum([x](unsigned long long int i) -> long double { return /*Taylor term here*/; });
if (!isfinite(series_sum)) cout << "Series does not converge!" << endl;
else {
cout << "Series converged, its value is : " << series_sum << endl;
cout << "Compared to sin : " << sinl(x) << endl;
}
}
:自己实践概念
,我试图限制模板仅接受以unsigned long long int
作为输入的lambda,以及long double
作为输出。这是我当前的尝试(无法编译):
template<typename T,integral ARG>
concept my_lambda = requires(T t, ARG u) {
{ return t(u); };
}
template<my_lambda ftn>
long double Taylor_sum(ftn term) { //The rest is same...
我用 google 搜索了各种来源,但在我看来,由于 concept
是 C++20 中相对较新的功能,因此可用的材料似乎较少。有谁知道如何正确限制我的模板参数?
Inspired by other question to calculate taylor series of a function(Original question), I wrote a template without any constraint to successfully calculate the sum. Here is current code (Template body removed, as @Elliott says it's irrelevant to the point..):
#include <iostream>
#include <cmath>
#include <limits>
template<typename ftn>
long double Taylor_sum(ftn terms_to_sum) { /* Summation calculation goes here... */ return result; };
int main(){
using namespace std; long double x; cin >> x ;
long double series_sum = Taylor_sum([x](unsigned long long int i) -> long double { return /*Taylor term here*/; });
if (!isfinite(series_sum)) cout << "Series does not converge!" << endl;
else {
cout << "Series converged, its value is : " << series_sum << endl;
cout << "Compared to sin : " << sinl(x) << endl;
}
}
Although the code works enough, to study & practice the concept
myself, I am trying to constrain the template to accept only lambda with unsigned long long int
as a input, and long double
as output. Here is my current attempt (which does not compile):
template<typename T,integral ARG>
concept my_lambda = requires(T t, ARG u) {
{ return t(u); };
}
template<my_lambda ftn>
long double Taylor_sum(ftn term) { //The rest is same...
I googled various sources, but it seems to me that because the concept
is relatively new feature in C++20, there seems less material available. Does anyone know how to constrain my template parameter properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将复合要求与return-type-requirement:
演示
You can use compound requirements with return-type-requirement:
Demo
对我来说,解决方案是 std::convertible_to 和 std::function 看起来相当简洁:
To me, a solution with std::convertible_to and std::function looks quite concise: