tinkerbeast
tinkerbeast

Reputation: 2067

Simple C++ interface to concepts example

I have an interface as follows:

struct TestInterface 
{
    void on_read(unsigned len, const char* buf);
};

My attempt at expressing this as a concept is as follows:

template<class T>
concept TestConcept = requires(T a)
{
    { a.on_read(unsigned, const char*) } -> void;
};

However, this does not compile. What is the correct syntax for this?

Errors I am getting are:

error: expected primary-expression before ‘unsigned’
error: expected primary-expression before ‘const’
error: return-type-requirement is not a type-constraint

As a side question, is there a way to enforce public / private members when declaring concepts?

This question might be too basic, please guide me.

Upvotes: 2

Views: 749

Answers (1)

Klaus
Klaus

Reputation: 25603

Two problems:

  • you have to use the objects not the types in the parameter list of the method to check
  • you have to check the type with SFINAE expression because the return type itself did not result in failure if it is different to the expected one.
struct TestInterface
{
    void on_read(unsigned len, const char* buf);
};

struct TestInterface2
{
    int on_read(unsigned len, const char* buf);
};

struct TestInterface3
{
    void on_read(unsigned len, const int* buf);
};

struct TestInterface4
{
    private:
    void on_read(unsigned len, const int* buf);
};

template<class T>
concept TestConcept = requires(T a)
{
    { a.on_read(unsigned{},std::declval<const char*>()) } -> std::same_as<void>;
};

int main()
{
    std::cout << TestConcept<TestInterface> << std::endl;
    std::cout << TestConcept<TestInterface2> << std::endl;
    std::cout << TestConcept<TestInterface3> << std::endl;
    std::cout << TestConcept<TestInterface4> << std::endl;
}

The method must be public to get the concept be valid as the expression a.on_read() also checks that the method is accessible.

If someone have an idea how to check for a private function, would be nice to give me a hint :-)

Upvotes: 2

Related Questions