定义一个函数签名,其中包含具有C++ 20个概念的参考
我正在尝试使用C ++ 20概念来限制接口。在此界面中,我希望功能签名仅使用引用。由于某种原因,我不能这样做。有人会帮忙吗?
#include <concepts>
template <typename T>
concept MyInterface = requires(T t)
{
// How do I specify a f(int&) instead of f(int) here?
{t.f(int{})} -> std::integral;
};
struct X
{
int f(int& i) {
return i;
}
};
static_assert(MyInterface<X>);
/*
** While tempting, this is _NOT_ a solution. **
template <typename T>
concept MyInterface = requires(T t, int& i) // Add a requirement here.
{
{t.f(i)} -> std::integral;
};
// This will compile, despite allowing `i` to be an int.
// When really, it should be a int&.
X::f(int i) { return i };
*/
I am trying to use C++20 Concepts to constrain an interface. In this interface, I want a function signature to only use references. For some reason, I can't do this. Would someone help?
#include <concepts>
template <typename T>
concept MyInterface = requires(T t)
{
// How do I specify a f(int&) instead of f(int) here?
{t.f(int{})} -> std::integral;
};
struct X
{
int f(int& i) {
return i;
}
};
static_assert(MyInterface<X>);
/*
** While tempting, this is _NOT_ a solution. **
template <typename T>
concept MyInterface = requires(T t, int& i) // Add a requirement here.
{
{t.f(i)} -> std::integral;
};
// This will compile, despite allowing `i` to be an int.
// When really, it should be a int&.
X::f(int i) { return i };
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不同意此评论,这绝对是一个解决方案(除非您不必使
i
int&amp;
,int
足够):也就是说,实际上是您的界面:您正在将lvalue
int
传递到成员函数f
中,并且您希望它返回某种满足Integral的类型代码>。
为了拒绝服用
int
的卡利斯,您必须通过一些不同的类型 - 例如可转换为int&amp;
的东西,而不是直接:或者另外拒绝其他情况:
传递
Reference_wrapper&lt; int&gt;
是...确定。明确拒绝服用int
rvalues似乎充其量似乎值得怀疑。I disagree with this comment, this is absolutely a solution (except you don't have to make
i
anint&
,int
suffices):That is, indeed, your interface: you're passing an lvalue
int
into the member functionf
and you expect it to return some type which satisfiesintegral
.In order to reject callees taking
int
, you have to either pass some different type - like something convertible toint&
instead of directly that:or then additionally reject the other case:
Passing
reference_wrapper<int>
is... ok. Explicitly rejecting takingint
rvalues seems questionable at best.您可以利用
std :: dectval
为约束创建参考类型:请注意,这仍然允许
t :: f(int)
工作。要禁止它,您可以对此添加另一个约束:You can utilize
std::declval
to create a reference type for the constraint:Note that this would still allow
T::f(int)
to work. To disallow it, you can add another constraint to it: