【问题标题】:C++ delegate templateC++ 委托模板
【发布时间】:2019-10-16 10:54:43
【问题描述】:

如果我有以下设置,只是示例。我遇到的问题是让模板的连接功能起作用。

class A
{
public:
   Delegate<void(int)> test;
};


class B
{
public:
    void test(int a)
    {
       std::cout << a;
    };

};

我想将此与以下内容联系起来: a.test.connect(&amp;b, &amp;B::test);

然后类a的实例可以调用class B实例上的测试函数。

我有以下模板,但无法捕获我需要的实例和函数。

#ifndef DELEGATE_H
#define DELEGATE_H

#include <functional>

template<class _Delegate>
class Delegate;


template<class R, class... Args>
class Delegate<R(Args...)>
{
public:
    template<typename T>
    void connect(T* t, R(Args... ) ) 
    {
        mFunction = std::function(T::*t, R(Args...));; 

    }

    R operator()(Args... args)
    {
        return mFunction(args...);
    }

protected:
    std::function<R(Args...)> mFunction;
};

#endif

【问题讨论】:

  • 请提供包含错误消息的minimal reproducible example。您的代码中有很多错误,例如Class AB::test 是私有的,在定义类 B 后缺少分号,...

标签: c++ templates delegates variadic-templates pointer-to-member


【解决方案1】:

你的connect() 应该写成这样

  template<typename T>
  void connect (T * t, R(T::*method)(Args...) ) 
   { mFunction = [=](Args ... as){ (t->*method)(as...); }; }

以下是完整的编译示例

#include <iostream>
#include <functional>

template <typename>
class Delegate;

template <typename R, typename... Args>
class Delegate<R(Args...)>
 {
   public:
      template<typename T>
      void connect (T * t, R(T::*method)(Args...) ) 
       { mFunction = [=](Args ... as){ (t->*method)(as...); }; }

      R operator() (Args... args)
       { return mFunction(args...); }

   protected:
      std::function<R(Args...)> mFunction;
 };

class A
 { public: Delegate<void(int)> test; };

class B
 { public: void test (int a) { std::cout << a; }; };

int main()
 {
   A a;
   B b;

   a.test.connect(&b, &B::test);

   a.test(42);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多