C++ bind2nd question
C++ bind2nd question
这是我期末考试中出现的一个问题。我不知道我该怎么做。我知道BindSecArg需要一个()操作符,但不确定里面是什么。
在这个问题中,您需要实现类似于std::bind2nd的东西。为简单起见,main使用" for "循环编写,但可以使用" for each "和STL容器重写。
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;
}
额外加分问题:你的实现很可能不工作(这是OK的!)
class Functor3 {
public:
std::string operator()(const std::string & i, const std::string & j) const {
return i+j;
}
};
STL如何解决这个问题?
BindSecArg
的operator()
需要接受一个参数(显然),它应该做的是调用"绑定"函子中的operator()
,传递给它(a)传入的"第一个"参数和(b)"绑定"的第二个参数。
看起来像:
template <typename T>
class BindSecArg
T toCall;
int second;
public:
// To initialize, we default-construct the bound-functor-instance, and copy the
// constructor parameter for our bound-parameter.
BindSecArg(int second): toCall(), second(second) {}
// To call, see the above discussion.
int operator() (int first) { return toCall(first, second); }
};
标准库(请不要说"STL")bind2nd
通过期望T是一个"AdaptableBinaryFunction"来解决这个问题,即提供一些typedef
成员识别operator()
的参数和结果类型,然后使用这些从使用这些类型作为模板类型的基类继承,然后使用基类提供的类型来模板自己的operator()
实现。这些是"模板元编程"的一些基本技术,它很快就会变得复杂起来。
可能有更好的实现:
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;
};
在我对你的问题的评论中发布的链接中,你可以找到stl代码
内部调用Functor.operator(),在其构造函数中将给定的值作为第二个参数传递给BindSecArg
。
相关文章:
- Leetcode 28 - Implement strStr(): question
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- VS2012 bind2nd 不是 std 的成员
- C 03中具有std :: bind2nd的复合函数
- 直接从bind1st和bind2nd中调用返回函子
- 如何在 Java 中模拟'question mark(?)'类型泛型以C++?
- 用户定义类的Bind2nd问题
- find_if 在 vector<Message*> 上,带有 bind2nd 和函子
- Use bind1st or bind2nd?
- c++ #ifdef Mac OS X question
- STL:为"const T &"类型调用带有ptr_fun的 bind2nd
- C++ bind2nd question
- 在转换中使用bind1st和bind2nd的问题
- Very Quick global .h Question(有了它,有些项目仍然没有定义)
- 出现至少两次的最长子字符串:c++ question
- RegGetValue Question
- bind1st and bind2nd
- const_iterator、find_if和bind2nd:对错误的调用不匹配
- borland builder c++ oracle question
- msdn bind2nd功能示例