Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to constrain my template to only accept lambda with specific input & output type?

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 term) { /* 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 powl(-1.0L,i)*powl(x,2ULL*i+1ULL)/tgammal(2ULL*i+2ULL); });
    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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I am trying to constrain the template to accept only lambda with
unsigned long long int as a input, and long 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...

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading