0

I am trying to write a helper class that would work with any kind of container of integers. Specifically, my class would lookup container values based on some criteria. In order to work with different types of containers, my class obviously needs to operate not on containers themselves but on container iterators. I am confused how to properly define and use this class.

   template<class ForwardIt>    // Do I have to template entire class?
    class MyLookup {
       public: 
       template<class ForwardIt>   // Or may I just template the constructor
       MyLookup(ForwardIt begin, ForwardIt end, ...)
    }

Implementation is such that only class constructor needs to get begin/end iterator pair. My questions are:

  1. Do I have to template entire class or may I template just the constructor?
  2. What is the correct way to instantiate the class? Compiler dislikes

    MyLookUp< std::vector< int>::iterator> lookup(foo.begin(), foo.end(), ...)

THIS QUESTION WAS SUPERSEDED BY ANOTHER ONE

Community
  • 1
  • 1
LRaiz
  • 667
  • 7
  • 18
  • 1
    If there's no data in the class that depends on template parameter, then just having template member functions is okay. However, if the class doesn't have any data at all, you might as well make all member functions `static`, and if you do that *and* don't have any private member functions, then you might as well skip using a class and instead use a `namespace`. – Some programmer dude Jul 23 '14 at 15:02
  • @JoachimPileborg thanks. No data in the class depends on template parameter, however the class does have some data. That is why I am trying to have template parameter passed/used only by the constructor. – LRaiz Jul 23 '14 at 17:16

1 Answers1

1

For 1. Templating just the constructor is ok, and have a nice side effect: you will not need to specify template parameters, because they will be detected.

For 2. If you stick with templating the class, you have a small problem in

MyLookUp< std::vector::iterator> lookup(foo.begin(), foo.end(), ...)

std::vector is not a type, but a template. You need to say e.g.

MyLookUp< std::vector<int>::iterator> lookup(foo.begin(), foo.end(), ...)
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • Actually I instantiate my class just like you indicated (stackoverflow showed my code incorrectly by skipping until I inserted a space after <). At any rate CLang complains error: expected unqualified-id when I write MyLookup ::iterator> lookup(index.begin(), index.end()); – LRaiz Jul 23 '14 at 17:06
  • Just realized that instead of "class" in template constructor I should use "typename". std::vector::iterator is not a class. Still the same CLang error "expected unqualified-id" upon instantiation. – LRaiz Jul 23 '14 at 18:22