C ++ How to make a generic pointer to an object

introduction

This is a small problem encountered in the code, there is no answer found online, then share it after you resolve to help a friend with the same problem

Straight into the subject's look at a simple piece of code to the introduction of our problems

    template<typename Type>
    struct wrapper_type{
        Type fun;
        ...
    };

? First of all this is to declare a simple generic object, if there is a demand now is that we need a smart pointer to a generic object of it, you might say, as usual is not good enough, maybe you mean:

    template<typename Type>
    struct wrapper_type{
        Type fun;
        ...
    };
	std::unique_ptr<wrapper_type<Type>> ptr_to_wrapper;

Unfortunately wrong is ridiculous, this Type above class declaration type is far worse, and even the scope is not the same, how can we do it, the solution is to inherit:

    struct base_type{
		...
    };
    std::unique_ptr<base_type> ptr;
    template<typename T>
    struct wrapper_type : base_type{
        T fun;
        ...
    };

So that we can successfully point, you might say that what use is it, for a relatively straightforward example, when we concurrent programming, we might have a callable object as interface when, under normal circumstances std :: function performs well, but we have to note that the fact that std :: function is replicable movable, and concurrent programming we commonly used in std :: packaged_task is movable can not be copied, which means we to pass a std :: packaged_task when we can not use the interface std :: function, this time we need to write a wrapper class, more skills came in handy

class function_wrapper{
    struct base_type{
        virtual void call() = 0;
        virtual ~base_type() {}
    };
    std::unique_ptr<base_type> ptr;
    
    template<typename T>
    struct wrapper_type : base_type{
        T fun;
        wrapper_type(T&& f) : fun(std::move(f)){}
        void call() override {fun();}
    };

    public:
        template<typename T>
        function_wrapper(T&& f) :
            ptr(new wrapper_type<T>(std::move(f))){}
        
        function_wrapper() = default;
        function_wrapper(function_wrapper&& f) : ptr(std::move(f.ptr)){}
        void operator()() {ptr->call();}
        function_wrapper& operator=(function_wrapper&& f){
            ptr = std::move(f.ptr);
            return *this;
        }

        function_wrapper(const function_wrapper&) = delete;
        function_wrapper(function_wrapper&) = delete;
        function_wrapper& operator=(const function_wrapper&) = delete;
};


参考:
C++ concurrency in action

Published 93 original articles · won praise 69 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43705457/article/details/104109952