jeudi 24 août 2017

Pass pointer to member function as argument with C++11

In an effort to optimize my code below, it seems to me that it would be beneficial if I could pass a pointer to the member functions str1 and str2 as pointers.

Is there a preferred way to do that in C++11? Or do you suggest a different strategy?


#include <iostream>
#include <vector>
#include <map>

class Base
{
  private:
    std::map<int, std::string> m_base1, m_base2;
    std::vector<std::string> m_str1 = {"one", "two", "three"};
    std::vector<std::string> m_str2 = {"four", "five", "six"};

  public:
    std::vector<std::string> &str1() { return m_str1; }
    std::vector<std::string> &str2() { return m_str2; }

    std::map<int, std::string> &base1() { return m_base1; }
    std::map<int, std::string> &base2() { return m_base2; }
};

template <typename T>
void fill_vec(T *b)
{
    size_t counter = 0;
    for (const auto &str_iter : b->str1())
        (b->base1())[counter++] = str_iter;

    counter=0;
    for (const auto &str_iter : b->str2())
        (b->base2())[counter++] = str_iter;
}

int main(int argc, char *argv[])
{
    Base *b = new Base;
    fill_vec(b);

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire