What is the type of back_inserter(container)?

S

suresh

Hi
My following code compiles but I do not know how to write this without using decltype. I have written my failed attempts in commented lines below the line which uses decltype.My motivation is the STL copy algorithm which accepts an output iterator as the 3rd argument.

Thanks
suresh

#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

template<class Out>
class Fill{
public:
Fill(){}
void fill(Out x){
for(int i = 0; i != 10; i++)*x++ = i;
}
};

int main(){
vector<int> v;

Fill<decltype(back_inserter(v))> f; //works

//does not work
//Fill<vector<int>::iterator> g;

//does not work
//Fill<back_insert_iterator<vector<int>> h;


f.fill(back_inserter(v));
copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
}
 
S

suresh

I figured it out. While declaring the variable 'h', I missed one right angled bracket...The correct definition would be,

Fill<back_insert_iterator<vector<int>>> h;

suresh
 
S

SG

Hi
My following code compiles but I do not know how to write this without
using decltype. [...]

template<class Out>
class Fill{
public:
  Fill(){}
  void fill(Out x){
    for(int i = 0; i != 10; i++)*x++ = i;
  }
};

Since you only use Out in the fill function, the class does not need
to be a template. You can let the compiler figure out the type on its
own. Then again, why is Fill even a class? Make it

template<class Out>
void fill(Out x)
{ ... }

Good old template argument deduction removes the need for decltype
here.
int main(){
  vector<int> v;
  Fill<decltype(back_inserter(v))> f; //works

// No need to specify what "Out" is
fill(back_inserter(v));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top