Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 concepts how to define existence of a function with arguments?

In C++20, we can now use concepts instead of SFINAE to figure out whether a function exists in a template typename:

template<typename T> concept fooable = requires (T a) {
    a.foo();
};

class Foo {
public:
    // If commented out, will fail compilation.
    void foo() {}
    void bar() {}
};

template <typename T> requires fooable<T>
void foo_it(T t) {
    t.bar();
}

int main()
{
    foo_it(Foo());
}

How do we do this with functions that have non-empty arguments?

like image 221
OneRaynyDay Avatar asked Sep 06 '25 03:09

OneRaynyDay


2 Answers

You might have extra parameters in requires:

template<typename T> concept fooable = requires (T a, int i) {
    a.foo(i);
};

Demo

like image 113
Jarod42 Avatar answered Sep 07 '25 23:09

Jarod42


The best option seems to be declval:

template<typename T> concept fooable = requires (T a) {
    a.foo(std::declval<int>());
};

class Foo {
public:
    void foo(int x) {}
    void bar() {}
};

template <typename T> requires fooable<T>
void foo_it(T t) {
    t.bar();
}

int main()
{
    foo_it(Foo());
}
like image 43
OneRaynyDay Avatar answered Sep 07 '25 23:09

OneRaynyDay