我的界面如下:
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/