mercredi 5 août 2020

Template to Bind non-member static function alongside with member function

I have a class that stores Dispatched commands in a queue and invokes them later. Command processor is a template class Encoder, it uses its method Encoder::Encode to process a command. But it can be either a member or a static non-member function. How can I bind it?

// specialization that have deduced Encoder's arguments
template <class Encoder, typename ... ArgsT>
class SerialCommunicator<Encoder, std::tuple<ArgsT...>>
{

    // ...
    Encoder encoder_;
    std::queue<std::function<EncodeResult(QByteArray&)> commands_;
    mutable std::mutex commandsMutex_;

public:
    // ...

    void Dispatch(ArgsT ... args)
    {
        std::lock_guard<std::mutex> lg{commandsMutex_};
        commands_.emplace(std::bind(&Encoder::Encode, &encoder_, std::placeholers::_1, 
                std::forward<ArgsT>(args)...);
    }

    // ...
};

With C++17 I would be able to use if constexpr(std::is_member_function_pointer_v<&Encoder::Encode>) block to pass a pointer to Encoder in case we deal with a member function pointer.

Aucun commentaire:

Enregistrer un commentaire