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

北战南征 提交于 2020-01-14 10:42:54

问题


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";
}

回答1:


You are testing for presence of a static member function. What you want is

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



回答2:


Try calling it yourself:

Test::func1();

prog.cc: In function 'int main()':
prog.cc:19:14: error: cannot call member function 'int Test::func1()' without object
   19 |  Test::func1();
      |              ^

Oh, right. func1 should either be a static member function, or you should call it on an instance inside your concept:

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


来源:https://stackoverflow.com/questions/58394556/c-concepts-can-i-have-a-constraint-requiring-a-function-be-present-in-a-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!