我发布了this answer,其中包含代码:
template <typename T>
auto vertex_triangle(const size_t index, const vector<pair<T, T>>& polygon) {
const auto& first = index == 0U ? polygon.back() : polygon[index - 1U];
const auto& second = polygon[index];
const auto& third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U];
return [&](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
}
我认为first
,second
和third
可以真正用作lambda标识符,如下所示:
[first = index == 0U ? polygon.back() : polygon[index - 1U],
second = polygon[index],
third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U]](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
但我只想通过不断的参考来捕捉。如果没有在标识符中指定类型,我该怎么做?
答案 0 :(得分:4)
你不能 1 。没有地方可以在lambda捕获列表中放置cv-qualifier。您可以查看relevant grammar:
init-capture: identifier initializer & identifier initializer
您也无法在捕获列表中指定类型(请参阅上面的语法)。
然而,您可以通过在名称前放置&
来捕获非const引用:
[&first = index == 0U ? polygon.back() : polygon[index - 1U],
&second = polygon[index],
&third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U]](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
或者只是坚持你的第一个片段,这也是IMO更具可读性。
1 polygon
为const
,因此在您的情况下,first
,second
和third
实际上是{{} 1}}如果你通过捕获列表中的引用捕获它们!但是,如果它不是,那么不,由于上述原因。