This was one of the questions showed up on my Final exam. I can't figure out what I'm supposed to do. I know BindSecArg requires a () operator, but not sure what goes inside.
In this question you are required to implement something similar to std::bind2nd. For simplicity main is written using a ”for”-loop, but it may be rewritten with ”for each” and STL containers.
class Functor1 {
public:
int operator()(const int & i, const int & j) const {
return i+j;
}
};
class Functor2 {
public:
int operator()(const int & i, const int & j) const {
return i*j;
}
};
template <typename T>
class BindSecArg
};
int main () {
Functor1 f1;
for (int i=0; i<10; ++i) std::cout << f1(i,i) << " "; //0 2 4 6 8 10
std::cout << std::endl;
Functor2 f2;
for (int i=0; i<10; ++i) std::cout << f2(i,i) << " "; //0 1 4 9 16 25
std::cout << std::endl;
BindSecArg<Functor1> b1(4); //bind second argument of Functor1 to 4
for (int i=0; i<10; ++i) std::cout << b1(i) << " "; //4 5 6 7 8 9
std::cout << std::endl;
BindSecArg<Functor2> b2(4); //bind second argument of Functor2 to 4
for (int i=0; i<10; ++i) std::cout << b2(i) << " "; //0 4 8 12 16 20
std::cout << std::endl;
}
Extra credit question: your implementation most probably doesn’t work (which is OK!) with
class Functor3 {
public:
std::string operator()(const std::string & i, const std::string & j) const {
return i+j;
}
};
how does STL solve this problem?
probably there are better implementations:
template <typename T>
class BindSecArg
{
public:
BindSecArg(int value2) : m_value2(value2){ };
int operator()(int value1) { return T()(value1, m_value2);}
private:
int m_value2;
};
int the link I posted in the comment to your question you can find the stl code.