问题描述
这段代码发生了什么?是这么混乱。
What is happening in this code? Is so confusing.
#include <utility>
struct check
{
template <typename T>
auto foo() -> decltype(std::declval<T>().value, void())
{
static_assert(T{}.value == 10, "Incorrect value");
}
} var;
int main()
{
struct apple
{
int value{10};
};
var.foo<apple>();
}
特别是它具有 - >
和之后的一切。
Specifically the part where it has ->
and everything after that.
推荐答案
auto foo() -> decltype(std::declval<T>().value, void())
尾随返回类型。它允许使用参数,但在这里没有必要。我想这写得更清楚。 decltype
查找表达式的类型,但该表达式实际上未评估。 std :: declval
用于创建传递给它的类型的实例。这里使用逗号运算符来生成总体返回类型 void
,因为逗号运算符计算左侧,抛弃它,计算右侧并返回。
This is a trailing return type. It's allowed to use parameters, but here that isn't necessary. I'd guess it's written like that to be clearer. decltype
finds the type of the expression inside, but that expression is not actually evaluated. std::declval
is used for creating an instance of the type passed to it. The comma operator is used here to make the overall return type void
, since the comma operator evaluates the left side, throws it away, evaluates the right side, and returns that.
第一部分创建了一种SFINAE(虽然我从来没有见过它像这样使用)。例如,如果你有一个 foo
的重载与 value2
而不是 value
,则不会有任何歧义。有关我的意思,请参见。将它与比较,只有一个返回类型 void
并导致错误。
The first part creates a sort of SFINAE (though I've never seen it used like this). For example, if you had an overload of foo
that did the same with value2
instead of value
, there would be no ambiguity of which to call. See here for what I mean. Compare it to this one, which just has a return type of void
and causes errors.
static_assert(T{}.value == 10, "Incorrect value");
此行确保 T
的值
成员的值为10.如果没有,则生成该文本的编译器错误。
This line makes sure a value-initialized instance of T
has its value
member have a value of 10. If it doesn't, a compiler error with that text is generated.
} var;
这只是该类的一个全局对象。
This is just a global object of that class to use.
struct apple
{
int value{10};
};
这是一个测试类的示例类。它有一个 value
成员,该成员在一个值初始化实例中是10(默认初始化的)。
This is a sample class to test it with. It has a value
member and that member is 10 in a value-initialized instance (default-initialized as well).
var.foo<apple>();
这只是调用函数。
这篇关于什么 - >一个函数原型是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!