这是我期末考试中出现的问题之一。我不知道我该怎么做。我知道BindSecArg需要一个()运算符,但不确定里面是什么。
在这个问题中,你需要实现一些类似于std::bind2nd的东西。为简单起见,main是使用“For”-loop编写的,但它可以用“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;
}额外的学分问题:你的实现很可能不能工作(这没问题!)使用
class Functor3 {
public:
std::string operator()(const std::string & i, const std::string & j) const {
return i+j;
}
};STL是如何解决这个问题的?
发布于 2011-07-23 18:39:54
也许有更好的实现:
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代码。
发布于 2011-07-23 18:47:06
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“来解决这个问题,即提供一些标识operator()的参数和结果类型的typedef成员,然后使用这些成员来继承基类(使用这些typedefs作为模板类型),然后使用基类提供的typedefs来为自己的operator()实现提供模板。这些是“模板元编程”的一些基本技术,而且它很快就变得复杂起来。为此,您应该查找一些单独的阅读资源。
发布于 2011-07-23 18:37:29
内部调用Functor.operator(),在其构造函数中传递给BindSecArg的值作为第二个参数。
https://stackoverflow.com/questions/6799755
复制相似问题