英文:
What is the meaning of function`->decltype()`
问题
我看到了这个函数,但完全不知道它在做什么:
template
auto MaxElement(Container &c, int num_of_el) -> decltype(c[0]){
int index = 0;
for (int i = 1; i < num_of_el; i++)
if (c[i] > c[index])
index = i;
return c[index];
}
这里是程序的主要部分:
int main(){
int a = 7;
vector<decltype(a)> v;
v.push_back(a);
a = 10;
v.push_back(5);
cout << v[0] << " " << v[1] << endl;
MaxElement(v, v.size()) = 10;
cout << v[0] << " " << v[1] << endl;
return 0;
}
我不明白`MaxElement`函数的工作原理有什么问题,但是`->decltype(c[0])`这样的东西是什么意思?另外,像`MaxElement(v, v.size()) = 10`这样的操作是如何实现的?发生了什么?
英文:
I've seen this one function I have no idea what's going on here:
template <typename Container>
auto MaxElement(Container &c,int num_of_el)->decltype(c[0]){
int index=0;
for(int i=1;i<num_of_el;i++)
if(c[i]>c[index])
index=i;
return c[index];
}
This here is the main part of the program:
int main(){
int a=7;
vector<decltype(a)> v;
v.push_back(a);
a=10;
v.push_back(5);
cout<<v[0]<<" "<<v[1]<<endl;
MaxElement(v,v.size())=10;
cout<<v[0]<<" "<<v[1]<<endl;
return 0;
}
I don't have a problem understanding how MaxElement function works, but rather with things like ->decltype(c[0])
? What does that do? Also how can we do something like MaxElement(v,v.size())=10
, what happens here?
答案1
得分: 5
->decltype(c[0])
?这是什么意思?
与返回类型为 auto
结合使用时,它声明函数的返回类型与 c[0]
的类型相同,即 int&
。
在这种情况下,它意味着函数的类型与 Container
中元素的引用类型相同。
这有助于 C++11 编译器,因为仅使用 auto
无法推断出这个类型。
一个简化的示例:
在 C++11 中,这不起作用:
template<typename Container>
auto foo(Container& c) { // 在 >= C++14 中,auto 是 `int`
return c[0];
}
但是这样可以:
template<typename Container>
auto foo(Container& c) -> decltype(c[0]) { // auto 是 `int&`
return c[0];
}
另外,我们如何做类似 MaxElement(v, v.size()) = 10
的操作?这里会发生什么?
在返回非 const
引用的函数中,您可以像对待任何其他对象一样对其进行赋值。
请注意,在 C++14 及以后版本中,如果没有尾随的 decltype(C[0])
,auto
不会返回对返回的对象的引用。它将以 by-value 的方式返回它,然后赋值将无法编译通过。
英文:
> ->decltype(c[0])
? What does that do?
In combination with auto
as the return type, it declares the return type of the function to be of the same type as c[0]
, which is an int&
.
In this case, it means that the type of the function has the same type as a reference to an element in the Container
.
This is to help C++11 compilers which can't deduce this with just auto
.
A simplified example:
This doesn't work in C++11:
template<typename Container>
auto foo(Container& c) { // auto is `int` in >= C++14
return c[0];
}
But this does:
template<typename Container>
auto foo(Container& c) -> decltype(c[0]) { // auto is `int&`
return c[0];
}
> Also how can we do something like MaxElement(v,v.size())=10
, what happens here?
In a function returning a non-const
reference to an object, you can assign to that object like any other.
Note that auto
(without the trailing decltype(C[0])
in C++14 and forward) will not return a reference to the returned object. It'll return it by-value - and then the assignment would not compile.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论