我正在努力找出为什么我无法进行转换以使用模板类。
这是模板类的简化版本:
template<typename T>
class base
{
public :
base() : all_() {}
~base() {}
public:
bool add(T t)
{
typename vector<T>::iterator itr
= lower_bound(all_.begin(), all_.end(), t);
if ( itr == all_.end() || *itr != t )
{
all_.push_back(t);
cout << "ok" << endl;
return true;
}
cout << "failed" << endl;
return false;
}
static bool addTo(base<T> *c, T t)
{
return c->add(t);
}
private :
vector<T> all_;
};
这就是我尝试使用 transform 来捕获 add 成员函数的所有 bool 输出的地方:
main()
{
base<int> test;
vector<bool> results;
vector<int> toAdd;
toAdd.push_back(10);
toAdd.push_back(11);
toAdd.push_back(10);
transform( toAdd.begin(), toAdd.end(),
back_inserter(results),
bind1st( (bool(*)(base<int>*,int))base<int>::addTo, &test ) );
}
目标是使用 base::add 或 base::addTo 插入 toAdd 容器的每个成员,并在 vector 结果中捕获 bool 结果
最佳答案
尝试:
transform( toAdd.begin(), toAdd.end(),
back_inserter(results),
bind1st( mem_fun(&base<int>::add), &test ) );
问题不在于模板,而是 bind1st 依赖额外的支持才能工作(参见 http://www.sgi.com/tech/stl/AdaptableBinaryFunction.html )。据我所知,它永远不能对普通的旧函数指针进行操作。
boost::bind
可以做更多的事情,如果你想把它带进来的话。对于这种情况你不需要它,但是:mem_fun
变成一个非- 将静态成员函数转换为可适应的二元函数。 addTo
因此也不是必需的,但如果您确实需要在类似情况下使用静态成员函数,那么可以使用 ptr_fun
。
关于c++ - 如何将 std::transform 与模板一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1809816/