我正在使用通过迭代器接受范围的函数,类似于以下代码中的“printPoints”和“printPoints2”。到目前为止,“printPoints”可以接受Point对象的 vector /列表/等的迭代器,但是需要“printPoints2”来处理POINTER到Point对象的 vector /列表/等。有什么技巧可以编写更通用的功能来替换这两个功能?

提前致谢。

#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <memory>

struct Point {
    int x;
    int y;

    Point(int x, int y): x(x), y(y) {}
};

/*
 Is there a more versatile function to replace the following two?
 */
template <class Iter>
void printPoints(Iter begin, Iter end) {
    for(auto it=begin; it!=end; ++it)
        std::cout << "{" << it->x << " " << it->y << "}";
}
template <class Iter>
void printPoints2(Iter begin, Iter end) {
    for(auto it=begin; it!=end; ++it)
        std::cout << "{" << (*it)->x << " " << (*it)->y << "}";
}

int main()
{
    std::vector<Point> vecPoints = {{0,0}, {1,1}};
    std::cout << "vector of points: ";
    printPoints(vecPoints.begin(), vecPoints.end());
    std::cout << "\n";

    std::list<Point> listPoints = {{2,2}, {3,3}};
    std::cout << "list of points: ";
    printPoints(listPoints.begin(), listPoints.end());
    std::cout << "\n";

    std::vector<std::unique_ptr<Point>> vecPtrPoints;
    vecPtrPoints.push_back(std::make_unique<Point>(4,4));
    vecPtrPoints.push_back(std::make_unique<Point>(5,5));
    std::cout << "vector of pointers to point: ";

    // won't work because of "it->x" inside the function
    //printPoints(vecPtrPoints.begin(), vecPtrPoints.end());
    printPoints2(vecPtrPoints.begin(), vecPtrPoints.end());
    std::cout << "\n";
}

最佳答案

C++ 17来解救!

#include <type_traits>

template <class Iter>
void printPoints(Iter begin, Iter end) {
    for(auto it=begin; it!=end; ++it)
    {
        if constexpr (std::is_same_v<typename std::iterator_traits<Iter>::value_type, Point>)
        {
            std::cout << "{" << it->x << " " << it->y << "}";
        }
        else
        {
            std::cout << "{" << (*it)->x << " " << (*it)->y << "}";
        }
    }
}

如果没有c++ 17,则可以通过使用std::enable_if来实现相似的功能,以使两个printPoints函数具有相同的名称。

另一种方法是重构代码:
void printPoint(const Point& point)
{
    std::cout << "{" << point.x << " " << point.y << "}";
}

void printPoint(const std::unique_ptr<Point>& point)
{
    printPoint(*point);
}

template <class Iter>
void printPoints(Iter begin, Iter end) {
    for(auto it=begin; it!=end; ++it)
    {
        printPoint(*it);
    }
}

这有点冗长,但是可以在早期的c++标准中使用,对于新手c++程序员来说可能更容易理解。

选项3是两者的组合:
void printPoint(const Point& point)
{
    std::cout << "{" << point.x << " " << point.y << "}";
}

template <class Iter>
void printPoints(Iter begin, Iter end) {
    for(auto it=begin; it!=end; ++it)
    {
        if constexpr (std::is_same_v<typename std::iterator_traits<Iter>::value_type, Point>)
        {
            printPoint(*it);
        }
        else
        {
            printPoint(**it);
        }
    }
}

10-04 13:08