K.R*_*ark 2 c++ generics templates c++-concepts c++20
受到计算函数泰勒级数的其他问题(原始问题)的启发,我编写了一个没有任何约束的模板来成功计算总和。这是当前代码(模板主体已删除,正如 @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;
}
}
Run Code Online (Sandbox Code Playgroud)
尽管代码足够工作,但为了concept自己学习和练习,我试图限制模板仅接受 lambdaunsigned long long int作为输入和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...
Run Code Online (Sandbox Code Playgroud)
我用 google 搜索了各种来源,但在我看来,因为conceptC++20 中的功能相对较新,所以可用的材料似乎较少。有谁知道如何正确限制我的模板参数?
我试图限制模板仅接受 lambda
unsigned long long int作为输入和long double输出。
您可以将复合需求与return-type-requirement结合使用:
template<typename F>
concept my_lambda = requires(F f, unsigned long long int x) {
{ f(x) } -> std::same_as<long double>;
};
template<my_lambda ftn>
long double Taylor_sum(ftn term) { //The rest is same...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
460 次 |
| 最近记录: |