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?
CodePudding user response:
I am trying to constrain the template to accept only lambda with
unsigned long long int
as a input, andlong double
as output.
You can use compound requirements with 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...