Search code examples
c++template-meta-programmingc++-concepts

C++ Concepts - Can I have a constraint requiring a function be present in a class?


I have a simple code snippet below, which compiles using:

g++-9 -std=c++2a -fconcepts

This is trying to define a concept that requires the presence of a function. I would expect the output to be "yes" but it's not... Any idea why? Thanks.

#include <iostream>


template <typename T>
concept bool HasFunc1 = 
    requires(T) {
        { T::func1() } -> int;
    };

struct Test
{
    int func1()
    {
        return 5;
    }
};

int main()
{
    if constexpr (HasFunc1<Test>)
        std::cout << "yes\n";
}

Solution

  • You are testing for the presence of a static member function, but func1 is not static. What you want is

    template <typename T>
    concept bool HasFunc1 = 
      requires(T t) {
          { t.func1() } -> int;
      };