M
M
Max Goncharenko2019-04-15 17:28:46
C++ / C#
Max Goncharenko, 2019-04-15 17:28:46

How to create a concept whose functions have type inference?

I am writing the next concept.

template <typename T>
concept bool Condition = requires(T a) {
    { a.match(...) } -> bool;
};

Quite simple: the concept obliges to have a match method. I want the type of the single match argument to be inferred by itself.
An example of a class that could satisfy such a concept:
class A {
public:
    template <typename T>
    bool match(T&& t) {
        t == 1;
    }
};

Question: how to specify automatic inference of the argument type in the concept? (what should be instead of "..."?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2019-04-15
@reverse_kacejot

The concept must be applied to the calling code. I slightly modified your example for the general case. Now they can check if any class contains a match method with a certain signature:

template <class T, class V>
concept bool HasMethodMatch = requires(T a, V v) {
    { a.match(v) } -> bool;
};

class A {
public:
    template <class T>
    bool match(T t) const {
        return t == 1;
    }
};

template <class V> 
    requires HasMethodMatch<A, V>
void doSmth(const A& a, V v)
{
    a.match(v);
}

int main()
{
    A a;
    doSmth(a, 5);
    doSmth(a, 5.f);
    doSmth(a, 5.d);
}

For a more general case, in the doSmth method, class A can be replaced with another template parameter. But, I think the logic is more or less clear now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question