you*_*ing 1 c++ templates stl stl-algorithm
我正在努力找出为什么我无法转换为使用模板类.
这是模板类的简化版本:
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_;
};
Run Code Online (Sandbox Code Playgroud)
这是我尝试使用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 ) );
}
Run Code Online (Sandbox Code Playgroud)
目的是使用base :: add或base :: addTo插入toAdd容器的每个成员,并在向量结果中捕获bool结果
尝试:
transform( toAdd.begin(), toAdd.end(),
back_inserter(results),
bind1st( mem_fun(&base<int>::add), &test ) );
Run Code Online (Sandbox Code Playgroud)
问题不在于模板,而是bind1st依赖于额外的工作支持(参见http://www.sgi.com/tech/stl/AdaptableBinaryFunction.html).AFAIK它不能在普通的旧函数指针上运行.
boost::bind如果你想把它带进来,可以做更多的事情.对于这种情况你不需要它,但是:mem_fun将非静态成员函数转换为自适应二进制函数.addTo因此也不需要,但是如果你确实需要在类似情况下使用静态成员函数那么就可以了ptr_fun.