Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

algorithm - Confused trying to write a generic helper class

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(), ...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...