Расширьте пакет параметров шаблона нетипичного типа с помощью «объявления объявления» (реализация Variadic шаблона во время компиляции SignalSlot) - PullRequest
0 голосов
/ 31 января 2019

Есть предложения по улучшению названия?

В Qt есть хорошая функция для сигналов и слотов.Однако он сообщает вам, может ли определенный сигнал быть подключен к определенному слоту только во время выполнения (afc).

Intend:

  • создание из шаблона класса, содержащего«Сигнальные сигнатуры» (указатели функций в качестве параметров шаблона), позволяющие подключать «слоты» данных сигнатур (количество и типы передаваемых аргументов) только к «определенным» сигналам с аналогичными сигнатурами;

  • должно быть простым в использовании.

Проблемы сейчас: Я получаю ошибку компиляции с использованием объявления в классе ISignalSlotMap. шаблон множественного вариационного наследования с вариадиальнымтипы аргументов - здесь все отлично скомпилировано.

Также есть ли способ упростить шаблонный алгоритм?

ОБНОВЛЕНИЕ: первый блок может быть скомпилирован и запущен без dll

Это может быть скомпилировано без ссылки на DLL

#include <iostream>
#include <type_traits>
#include <forward_list>
#include <memory>

//template wrapper
template <typename...>
struct TW
{};


//template to get Class type from pointer
template <class ReturnType, class ... ArgTypes>
constexpr ReturnType ClassFromPointer(void(ReturnType::*)(ArgTypes...));


//template to get pack of arguments' types
template <class ReturnType, class ... ArgTypes>
constexpr TW<ArgTypes...> ArgTypesPackFromPointer(void(ReturnType::*)(ArgTypes...));

template <auto ptr>
using FuncClass = decltype(ClassFromPointer(ptr));

template <auto ptr>
using FuncPack = decltype(ArgTypesPackFromPointer(ptr));


template <class ... ArgTypes>
struct Invoker
{
    virtual void Invoke(ArgTypes ... args) = 0;
};


template <class ClType, class ... ArgTypes>
class InvokerImpl : public Invoker<ArgTypes...>
{
    ClType *ptr_;
    void(ClType::*pFunc_)(ArgTypes...);

public:
    InvokerImpl(ClType* pObj, void(ClType::*pFunc)(ArgTypes...))
        : ptr_(pObj),
        pFunc_(pFunc)
    {}

    virtual void Invoke(ArgTypes ... args)
    {
        (ptr_->*pFunc_)(args...);
    }
};

template <class ClType, class ... ArgTypes>
Invoker<ArgTypes...>* CreateInvoker(ClType* pObj, void(ClType::*pFunc)(ArgTypes...))
{
    return new InvokerImpl<ClType, ArgTypes...>(pObj, pFunc);
}

template <class Pack>
class SlotContainerTranslated;

template <template <class ...> class Pack, class ... ArgTypes>
class SlotContainerTranslated<Pack<ArgTypes...>>
{
    typedef std::unique_ptr<Invoker<ArgTypes...>> pInvoker;
    std::forward_list<pInvoker> slots_;

public:
    void AddInvoker(Invoker<ArgTypes...>* pInv)
    {
        slots_.push_front(std::move(pInvoker(pInv)));
    }

    void DispatchSignal(ArgTypes ... args)
    {
        auto start = slots_.begin();
        while (start != slots_.end())
        {
            (*start)->Invoke(args...);
            ++start;
        }
    }
};

template <auto memfuncptr>
class ISlotContainer : SlotContainerTranslated<FuncPack<memfuncptr>>
{
public:
    using SlotContainerTranslated<FuncPack<memfuncptr>>::AddInvoker;
    using SlotContainerTranslated<FuncPack<memfuncptr>>::DispatchSignal;
};


template <auto ... memfuncPtrs>
class ISignalSlotMap : SlotContainerTranslated<FuncPack<memfuncPtrs>>...
{
public:
    //  using SlotContainerTranslated<FuncPack<memfuncPtrs>>::AddInvoker...;
    //  using SlotContainerTranslated<FuncPack<memfuncPtrs>>::DispatchSignal...;

};
////////////////////////////////////////////////////////////////////////

struct AlienSignals
{
    void MindControl() {};
    void MindControlPrint(int a, double b, int c, int d, const char* str) {};
    void MindControlAdvise(int i, bool b) {};
};



struct Alien
{
    static Alien* Invade();
    virtual ISlotContainer<&AlienSignals::MindControlAdvise>& AccessSignal() = 0;

    /*//this is what usage is expected to be like
    virtual ISignalSlotMap<&AlienSignals::MindControl,
        &AlienSignals::MindControlAdvise,
        &AlienSignals::MindControlPrint>& AccessSignalMap() = 0;
        */

    virtual ~Alien() = default;
};

class AlienImpl : public Alien
{
    std::unique_ptr<ISlotContainer<&AlienSignals::MindControlAdvise>> signalMindControlAdvise_
    { new ISlotContainer<&AlienSignals::MindControlAdvise> };

    // Inherited via Alien
    virtual ISlotContainer<&AlienSignals::MindControlAdvise>& AccessSignal() override
    {
        return *signalMindControlAdvise_;
    }

    virtual ~AlienImpl() = default;
};

Alien * Alien::Invade()
{
    return new AlienImpl;
}


struct Human
{
    int id = 0;

    Human(int i)
        : id(i)
    {}

    void Print()
    {
        std::cout << "Human: " << id << "! " << std::endl;
    }

    void mPrint(int a, double b, int c, int d, const char* str)
    {
        std::cout << "Human: " << id << "! " << a << " " << b << " " << c << " " << d << " " << str << std::endl;
    }

    void Advise(int i, bool b)
    {
        auto colour = b ? "red" : "blue";
        std::cout << "Human: " << id << "! I will take " << i << " of " << colour << " pills" << std::endl;
    }
};

template <auto memfuncptr>
constexpr auto GetType()
{
    return memfuncptr;
}

template <auto memfunc>
using PtrType = decltype(GetType<memfunc>());

int main()
{
    Human person1{ 1 }, person2{ 2 }, person3{ 3 };

    std::unique_ptr<Alien>alien{ Alien::Invade() };
    alien->AccessSignal().AddInvoker(CreateInvoker(&person1, &Human::Advise));
    alien->AccessSignal().AddInvoker(CreateInvoker(&person2, &Human::Advise));
    alien->AccessSignal().AddInvoker(CreateInvoker(&person3, &Human::Advise));
    alien->AccessSignal().DispatchSignal(42, false);

    return 0;
}

UPDATE2: Я обнаружил, что проблема заключается в расширении не-типашаблонный паритетameter pack, чтобы «использование» могло работатьЯ до сих пор не могу преодолеть эту проблему.

c ++ нетиповое расширение пакета параметров аналогичный вопрос, но о функциях.Я также не смог найти использования свертывания выражений с наследованием.

Есть ответ, который показывает многообещающий подход: https://stackoverflow.com/a/53112843/9363996

Но есть серьезные недостатки.Один использует шаблонную функцию для вызова унаследованных функций.Этот пример компилируется и работает, но:

  • Я не знаю, как принудительно генерировать методы из шаблонов в случае, если я хочу скомпилировать интерфейс для DLL;
  • Это оченьнеудобно из-за того, что intellisense не показывает, какие аргументы, какие аргументы ожидаются, и вы должны явно указать указатель функции.

ПРИМЕР 2

#include <iostream>

template <class ...>
struct TW {};

template <class ClType, class ... ArgTypes>
constexpr ClType ClassType(void(ClType::*)(ArgTypes...));

template <class ClType, class ... ArgTypes>
constexpr TW<ArgTypes...> ArgsType(void(ClType::*)(ArgTypes...));

template <auto pFunc>
using class_trait = decltype(ClassType(pFunc));

template <auto pFunc>
using args_trait = decltype(ArgsType(pFunc));

template <class, class>
struct _func_trait;

template <class ClType, template <class...> class Pack, class ... ArgTypes>
struct _func_trait<ClType, Pack<ArgTypes...>>
{
    typedef void(ClType::*FuncPtr)(ArgTypes...);
    typedef ClType ClassType;
    typedef Pack<ArgTypes...> Args;
};

template <auto pFunc>
struct func_traits : public _func_trait<class_trait<pFunc>, args_trait<pFunc>>
{};


template <auto L, class Pack>
struct ClassImpl;

template <auto L, template <class ...> class Pack, class ... ArgTypes>
struct ClassImpl<L, Pack<ArgTypes...>>
{
    void invoke(ArgTypes ... args)
    {
        (std::cout << ... << args) << std::endl;
    }
};

template <auto L, auto ...R>
class My_class;

template <auto L>
class My_class<L> : public ClassImpl <L, args_trait<L>>
{

};

template <auto L, auto ... R>
class My_class : public My_class<L>, public My_class<R...>
{
public:

    template <auto T, class ... ArgTypes>
    void Invoke(ArgTypes... args)
    {
        My_class<T>::invoke(args...);
        return;
    }

};



struct Signals
{
    void func1(int a, double b) {}

    void func2(const char*, const char*) {}

    constexpr void func3(int a, double b, int c, bool d);
};


int main()
{

    Signals s;
    My_class<&Signals::func1, &Signals::func2, &Signals::func3> mSignls;
    mSignls.Invoke<&Signals::func1>(4, 6.31);
    mSignls.Invoke<&Signals::func2>("Invoking funcion:", "function 2");

    return 0;
}

1 Ответ

0 голосов
/ 02 февраля 2019

Наконец-то я пришел к решению, его использование довольно простое, как я и хотел.

Вот мой рабочий пример!

#include <tuple>
#include <iostream>

template <class ...>
struct TW {};

template <class ClType, class ... ArgTypes>
constexpr ClType ClassType(void(ClType::*)(ArgTypes...));

template <class ClType, class ... ArgTypes>
constexpr TW<ArgTypes...> ArgsType(void(ClType::*)(ArgTypes...));

template <auto pFunc>
using class_trait = decltype(ClassType(pFunc));

template <auto pFunc>
using args_trait = decltype(ArgsType(pFunc));

template <class, class>
struct _func_trait;

template <class ClType, template <class...> class Pack, class ... ArgTypes>
struct _func_trait<ClType, Pack<ArgTypes...>>
{
    typedef void(ClType::*FuncPtr)(ArgTypes...);
    typedef ClType ClassType;
    typedef Pack<ArgTypes...> Args;
};

template <auto pFunc>
struct func_traits : public _func_trait<class_trait<pFunc>, args_trait<pFunc>>
{};


template <auto L, class Pack = args_trait<L>>
struct ClassImpl;

template <auto L, template <class ...> class Pack, class ... ArgTypes>
struct ClassImpl<L, Pack<ArgTypes...>>
{
    void invoke(decltype(L), ArgTypes ... args)
    {
        (std::cout << ... << args) << std::endl;
    }
};



template <class ... Impls>
struct ISignalMap : protected Impls...
{
    using Impls::invoke...;
};

template <auto ... L>
struct SignalsMap
{
    //just to see the pointers' values
    static constexpr std::tuple<decltype(L)...> t{ std::make_tuple(L...) };
    ISignalMap<ClassImpl<L>...> Signals{};
};

struct Signals
{
    void func1(int a, double b) {}
    void func12(int a, double b) {}

    void func2(double a, double b, int c) {}

    constexpr void func3(const char*) {}
};


int main(void)
{
    auto& ref = SignalsMap<&Signals::func1, &Signals::func2, &Signals::func3>::t;

    //add SignalsMap as member to your class and pass the pointers to
    //methods you need to be signals
    SignalsMap<&Signals::func1, &Signals::func2, &Signals::func3> sm;

    //first parameter is a pointer to a signal you want to invoke
    sm.Signals.invoke(&Signals::func2, 4.8, 15.16, 23);
    sm.Signals.invoke(&Signals::func1, 23, 42.108);
    sm.Signals.invoke(&Signals::func12, 23, 42.108);

    sm.Signals.invoke(&Signals::func3, "Eat this!");

    return 0;
}
...