【问题标题】:C++20 concepts how to define existence of a function with arguments?C ++ 20概念如何定义带参数的函数的存在?
【发布时间】:2020-05-28 07:01:03
【问题描述】:

在 C++20 中,我们现在可以使用概念而不是 SFINAE 来确定函数是否存在于模板类型名中:

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());
}

我们如何处理具有非空参数的函数?

【问题讨论】:

    标签: c++ c++20 c++-concepts


    【解决方案1】:

    requires 中可能有额外的参数:

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

    Demo

    【讨论】:

      【解决方案2】:

      最好的选择似乎是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());
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-15
        • 1970-01-01
        • 1970-01-01
        • 2021-04-11
        • 2022-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        相关资源
        最近更新 更多