So I am calling a helper function, vertex_triangle, quite a bit to allow me to take in a vector<pair<T, T>> and wind them into ordered triangles, then put those in a vector in that order. I'm using this as my return object:
template <Typename T>
struct Triangle {
Triangle(const pair<T, T>& first, const pair<T, T>& second, const pair<T, T>& third) {
data[0] = first;
data[1] = second;
data[2] = third;
}
pair<T, T> data[3];
};
So my winding helper function looks like this:
template<typename T>
triangle<T> vertex_triangle(const size_t index, const
vector<pair<T, T>>& polygon){
if (0 == index){
return Triangle(polygon.back(), polygon.front(), polygon[1]);
}else if (index == (polygon.size() - 1)){
return Triangle(polygon[polygon.size() - 2], polygon.back(), polygon.front());
}else{
return Triangle(polygon[index - 1], polygon[index], polygon[index + 1]);
}
}
Originally I was directly placing the return in a vector<Triangle<T>> foo like this all made sense:
foo.push_back(vertex_triangle(i, bar))
Now I need to use a vector<pair<T, T>> foo so I'd have to unpack the return of vertex_triangle:
const auto temp = vertex_triangle(i, bar);
foo.push_back(temp[0]);
foo.push_back(temp[1]);
foo.push_back(temp[2]);
But I don't really like the temporary object, is there a way to somehow return the order that I want push the verts from bar into foo without returning a copy of the points, unpacking them, and pushing them back one by one?
So your comment on using an out parameter is the most direct option here. The other alternative would be to return a lambda, which would capture your inputs by reference. So for example:
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); };
}
Could be called like this:
vertex_triangle(i, bar)(foo)
来源:https://stackoverflow.com/questions/47083657/return-ordering-without-a-vector