如何使用C ++ 03中的成员函数返回的值填充向量?

时间:2016-08-04 12:28:15

标签: c++ boost initialization c++03

我想得到与此相同的行为:

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));

上面的代码段出现以下错误:

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));

任何人都可以分享使用指向成员函数的指针初始化向量而不是构造然后在其中生成的方法吗?

3 个答案:

答案 0 :(得分:1)

这不起作用的原因:

std::bind1st(std::mem_fun(&IdentifiersGenerator::getNextIdentifiers), gen)

bind1st需要二进制函数,而您提供的是一元函数。没有预先打包的C ++ 03解决方案,如果boost::bind是我将使用的选项。

否则,可以编写自己的工厂,该工厂接受指向nullary成员函数的指针和指向该类的指针,并返回一个调用它的operator()对象。

答案 1 :(得分:0)

(此处仅供参考)

好的,所以我意识到我可以这样使用boost::bind

std::vector<AlarmIdentifiers> v(100);
std::generate(v.begin(), v.end(),
    boost::bind(&IdentifiersGenerator::getNextIdentifiers, &gen));

答案 2 :(得分:0)

bind真的是一个很老的&#39;并且大多是过时的方式来实现类似于更好的lambda语法。

IdentifiersGenerator gen;
std::vector<Identifiers> v(100);
std::generate(v.begin(), v.end(), [&](){ return gen.getNextIdentifiers(); });

你也可以使用generate_n