【发布时间】:2016-08-04 22:28:04
【问题描述】:
我希望得到与此相同的行为:
IdentifiersGenerator gen;
for(int i = 0; i < 100; ++i)
v.push_back(gen.getNextIdentifiers());
语法类似于:
IdentifiersGenerator gen;
std::vector<Identifiers> v(100);
std::generate(v.begin(), v.end(),
std::bind1st(std::mem_fun(&IdentifiersGenerator::getNextIdentifiers), gen));
上面的 sn-p 给出以下错误:
test/src/IdentifiersGeneratorTest.cpp:449: instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:100: error: no type named ‘second_argument_type’ in ‘class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>’
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:103: error: no type named ‘first_argument_type’ in ‘class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>’
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:106: error: no type named ‘first_argument_type’ in ‘class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>’
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:111: error: no type named ‘second_argument_type’ in ‘class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>’
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:117: error: no type named ‘second_argument_type’ in ‘class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>’
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h: In function ‘std::binder1st<_Operation> std::bind1st(const _Operation&, const _Tp&) [with _Operation = std::mem_fun_t<const Identifiers&, IdentifiersGenerator>, _Tp = IdentifiersGenerator]’:
test/src/IdentifiersGeneratorTest.cpp:449: instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/backward/binders.h:126: error: no type named ‘first_argument_type’ in ‘class std::mem_fun_t<const Identifiers&, IdentifiersGenerator>’
也许即使没有 std::vector 默认对象初始化也可以做到这一点,例如boost::make_function_input_iterator.
编辑好的,所以我意识到我可以像这样使用boost::bind:
std::vector<AlarmIdentifiers> v(100);
std::generate(v.begin(), v.end(),
boost::bind(&IdentifiersGenerator::getNextIdentifiers, &gen));
任何人都可以分享一种使用指向成员函数的指针来初始化向量的方法,而不是在其中构造然后生成?
【问题讨论】:
-
做一个仿函数可以吗?
-
不,我需要成员函数
IdentifiersGenerator::getNextIdentifiers -
你可以使用仿函数获得它。我在问你是否可以将调用包装在仿函数中。
-
@DimChtz
std::bind是 C++11,我已明确将此问题标记为 C++03。不过我可能会使用boost::bind
标签: c++ boost initialization c++03