简体   繁体   English

模板与类成员函数的正确使用

[英]Correct use of template with a class member function

the concept of templates is quite difficult to grasp quickly.模板的概念很难快速掌握。 I need a class member function to iterate over vector of any objects and print them all out.我需要一个类成员函数来迭代任何对象的向量并将它们全部打印出来。 Can I do this with using templates?我可以使用模板来做到这一点吗? Ie: IE:

    void SomeClass::printAll(std::vector< any type here> array) {
      for (auto & o : array) {
        std::cout << o << std::end;
    
      }   
    }

If this is possible in C++, how would I define it in the header and implementation files, I dare guess the syntax might be different.如果这在 C++ 中是可能的,我将如何在头文件和实现文件中定义它,我敢猜测语法可能会有所不同。

Many thanks in advance for helping with this naive questions.非常感谢您帮助解决这些幼稚的问题。

Trying to grasp any non-trivial topic quickly is difficult.试图快速掌握任何不平凡的话题是困难的。 Just don't do it, but go slowly.只是不要这样做,而要慢慢来。 That also means not trying to understand more than one thing at a time.这也意味着不要试图一次理解不止一件事。 I don't know why that function has to be member of a class.我不知道为什么该函数必须是类的成员。 Make it a free function:使其成为免费功能:

template <typename T>
void printAll(const std::vector<T>& vect) {
    for (const auto& o : vect) {
        std::cout << o << "\n";   
    }   
}

Don't pass by value when you can pass by const reference.当您可以通过 const 引用传递时,不要通过值传递。 I would prefer \\n here rather than std::endl (not std::end ) because std::endl flushes the stream.我更喜欢\\n而不是std::endl (不是std::end ),因为std::endl刷新流。 Choose names carefully, a std::vector is not an array.仔细选择名称, std::vector不是数组。

The above will only work with vectors, but it can be more flexible for example by passing iterators:以上仅适用于向量,但它可以更灵活,例如通过传递迭代器:

template <typename IT>
void printAll(IT begin, IT end) {
    for ( ; begin != end; ++begin) {
        std::cout << *begin << "\n";   
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM