我的类看起来像这样:
class A
{
public:
class variables_map vm /*! A boost::program_options variable map containing all program_options in use. */;
char sep_to_space(char c);
template <typename T>
void VectorFromOption(char * sOption, vector<T> & n);
};
char A::sep_to_space(char c){
return c == ',' || c == '<' || c == '>' ? ' ' : c;
}
template <typename T>
void A::VectorFromOption(char * sOption, vector<T> & n)
string s=A::vm[sOption].as<string>();
transform(s.begin(), s.end(), s.begin(), &A::sep_to_space );
stringstream ss(s);
copy(istream_iterator<T>(ss), istream_iterator<T>(), std::back_inserter(n));
}
这些在类外工作正常,但我找不到正确的方法来传递sep_to_space()
作为transform
的第 4 个参数,因为它们是类成员。如果我将它们注释掉,其他所有内容都可以正确编译和运行。
上述&A::sep_to_space
会产生一个神秘的错误:
1>c:Program Files (x86)Microsoft Visual Studio 9.0VCincludealgorithm(671) : error C2064: term does not evaluate to a function taking 1 arguments
怕目前在我的头上。建议?
为什么sep_to_space
甚至是A
的(非静态)成员?它不访问任何成员,显然不需要。使其成为自由函数或静态成员,一切都很好。
但是,若要回答一般问题,需要将成员绑定到调用它的对象。
一种选择是使用 C++11 或 Boost 中的bind
功能:
#include <functional> // or <boost/bind.hpp>
using std::placeholders::_1; // placeholder for the first argument
std::transform(s.begin(), s.end(), s.begin(), std::bind(&A::sep_to_space, this, _1));
或者,如果您已经有可用的 C++11,只需使用 lambda:
std::transform(s.begin(), s.end(), s.begin(),
[this](char c){
return sep_to_space(c);
});
尝试:
using std::placeholders::_1;
transform(s.begin(), s.end(), s.begin(), std::bind( &A::sep_to_space, this, _1));
(或提升::绑定)