Etush
Etush

Reputation: 3

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? I.e.:

    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.

Many thanks in advance for helping with this naive questions.

Upvotes: 0

Views: 59

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122420

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. I would prefer \n here rather than std::endl (not std::end) because std::endl flushes the stream. Choose names carefully, a std::vector is not an array.

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";   
    }
}

Upvotes: 3

Related Questions