概念示例的简单 C++ 接口
Simple C++ interface to concepts example
我的界面如下:
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 / 私有成员?
这个问题可能太基础了,请指导。
两个问题:
- 您必须使用对象而不是方法参数列表中的类型来检查
- 您必须使用 SFINAE 表达式检查类型,因为 return 类型本身不会导致失败,如果它与预期的不同。
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() 还会检查方法是否可访问。
如果有人知道如何检查私有函数,请给我提示:-)
我的界面如下:
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 / 私有成员?
这个问题可能太基础了,请指导。
两个问题:
- 您必须使用对象而不是方法参数列表中的类型来检查
- 您必须使用 SFINAE 表达式检查类型,因为 return 类型本身不会导致失败,如果它与预期的不同。
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() 还会检查方法是否可访问。
如果有人知道如何检查私有函数,请给我提示:-)