使用模板函数打印智能指针向量

Print smart pointer vector using a template function

我写了一个函数来打印给定的 vector

template <typename T>
void print_vector(std::string text, std::vector<T> &vect){
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(T &t: vect){
        std::cout << t << ", ";
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

但是当我给函数一个 vector of shared_ptr 时,它打印地址,而不是指向的值。

当元素是 shared_ptr 时,有没有办法打印值?
我尝试了以下方法,但它给了我一个编译错误,我不知道如何修复它。

template <typename T, typename F>
void print_vector(std::string text, std::vector<T> &vect){
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(T &t: vect){
        if(std::is_same<T, std::shared_ptr<F>>::value) {
            std::cout << *t << ", ";
        } else {
            std::cout << t << ", ";
        }
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

您可以为 shared_ptr 重载运算符,查看以下代码:

template<typename T>
ostream& operator<<(ostream& out, const shared_ptr<T>& s_ptr)
{
    if (s_ptr != nullptr)
        out << (*s_ptr);
    return out;
}

template <typename T>
void print_vector(std::string text, std::vector<T> &vect){
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(T &t: vect){
        std::cout << t << ", ";
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

您想为 shared_ptr 重载流运算符,这可以针对特定类型或所有类型:

template <typename T>
std::ostream& operator << (std::ostream& os, const std::shared_ptr< T >& p)
{
  if ( p )
  {
    os << *p;
  }
  else
  {
    os << "<null>";
  }
  return os;
}

为智能指针向量重载函数。

template <typename T>
void print_vector(std::string text, std::vector<T> &vect){
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(T &t: vect){
        std::cout << t << ", ";
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

template <typename T>
void print_vector(std::string text, std::vector<std::shared_ptr<T>> &vect){
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(auto &t: vect){
        std::cout << *t << ", ";
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

如果您在更多情况下希望打印不同的内容,您可能会发现某些重载不明确,您可能必须在它们应该相互匹配时禁用不明确的模板。

只需重载函数模板:

template <typename T>
void print_vector(std::string text, std::vector<T> &vect){
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(T &t: vect){
        std::cout << t << ", ";
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

template <typename T>
void print_vector(std::string text, std::vector<std::shared_ptr<T>> &vect) {
    std::cout << ">>>>>>>>>> " << text << " <<<<<<<<<<" << std::endl;
    for(auto &t: vect){
        std::cout << *t << ", ";
    }
    std::cout << std::endl << "--------------------" << std::endl;
}

现在它将处理这两种情况。