coliru.stacked-crooked.com

опрос на самом деле касаетсяуже заданный вопрос, Я попробовалответ дал @ r3mus n0x также видел некоторые вопросы SO, которые не помогли мне получить четкое представление о вышеупомянутой ситуации.

В данном посте отсутствует MCVE, поэтому я немного попробовал и придумал следующий код и с той же ошибкой, о которой @ user10213044 упомянул в своем посте.

Сообщение об ошибке

error C2065: 'm_func': undeclared identifier

Мой вопрос:

Q1: Можем ли мы действительно сохранить указатель на некоторые функции-члены класса (как в следующем примере) в свой закрытый член (например, векторный массив)? Если да, то в чем причина вышеуказанной ошибки?

Q2Я также попытался написать внутри цикла for:

classFuncPtr fun = bindClassPtr->m_func; // compiles
fun(str); // error

дал мне:Сообщение об ошибке

error: must use '.*' or '->*' to call pointer-to-member function in 'fun (...)', e.g. '(... ->* fun) (...)'
 fun(str); // error

чего я не мог понять. Кто-нибудь может сказать мне, что пошло не так в этом случае?

Вторая попытка была похожа на следующий случай, который мы используем для случая указателя на обычные функции.

typedef void(*FuncPtr)(const std::string&);
FuncPtr Lambda = [](const std::string& str) { std::cout << str << std::endl; };
Lambda(std::string("Hellow World"));

Вот код, который я пробовал:

#include <iostream>
#include <vector>
#include <string>
#include <memory>

cla,ss MyClass;          
typedef void (MyClass::*classFuncPtr)(const std::string&); // function ptr to MyClass::member functions

struct MyBind // bind struct
{
   classFuncPtr m_func;
   explicit MyBind(const classFuncPtr& func): m_func(std::move(func)) {}
};

class MyClass
{
    std::string m_var;
    std::vector<std::unique_ptr<MyBind>> my_binds_;
public:
   MyClass() // constructor 
   {
      my_binds_.emplace_back( std::make_unique<MyBind>( std::move(&MyClass::do_this) ));
      my_binds_.emplace_back( std::make_unique<MyBind>( std::move(&MyClass::do_that) ));
   }

   // two functions to bind
   void  do_this (const std::string& str) { std::cout << "From do this: " << str << std::endl;   }
   void  do_that (const std::string& str) { std::cout << "From do that: " << str << std::endl;   };

   void handle_input(const std::string& str)
   {

      for (const std::unique_ptr<MyBind>& bindClassPtr: my_binds_)
      {
          // how to print passed string str here??              (Q1)
          (bindClassPtr->*m_func)(str);

          /*
          classFuncPtr fun = bindClassPtr->m_func; // compiles   (Q2)
          fun(str); // error
          */
      }
   }
};

Ответы на вопрос(1)

Ваш ответ на вопрос