c++ - 概念示例的简单 C++ 接口(interface)

标签 c++ c++-concepts

我的界面如下:

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

我尝试将其表达为一个概念,如下:

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

但是,这无法编译。正确的语法是什么?

我遇到的错误是:

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

作为一个附带问题,在声明概念时是否有办法强制执行公共(public)/私有(private)成员?

这个问题可能太基础了,请指导我。

最佳答案

两个问题:

  • 必须使用对象而不是方法参数列表中的类型来检查
  • 您必须使用 SFINAE 表达式检查类型,因为如果返回类型与预期不同,则返回类型本身不会导致失败。
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;
}

该方法必须是公共(public)的才能使概念有效,因为表达式 a.on_read() 还会检查该方法是否可访问。

如果有人知道如何检查私有(private)函数,很高兴给我一个提示:-)

关于c++ - 概念示例的简单 C++ 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63313096/

相关文章:

c++ - 为什么采用迭代器的构造函数要求元素是 EmplaceConstructible?

c++ - Windows 上的 C++17 是否与 ubuntu 上的 C++17 一致?

c++ - 使用 ppl.h 查找最大值

c++ - 大 O 表示法中的 next_permutation 时间复杂度

c++ - 为什么概念会使 C++ 编译速度变慢?

c++ - 为什么 std::derived_from 概念是通过添加 cv 限定符的附加可转换性测试来实现的?

c++ - 数据成员的编译时重新安排?

c++ - 访问 map 元素会增加其分配的内存大小

c++ - 使用 C++ 在 OpenCV 中矩阵中的多维数据

C++ 2a - 多态范围