Variadic templates

前端 未结 8 1937
野趣味
野趣味 2020-12-06 00:05

I have seen a lot of links introducing the variadic templates. But I have never seen any compilable example that demonstrates this approach.

Could someone provide me

8条回答
  •  猫巷女王i
    2020-12-06 00:32

    Variadic templates are a C++0x feature that primarily targets authors of generic libraries. I would not expect to see them in "user code". For example, in the C++0x standard library they are used in a lot of places: std::function, std::async, std::reference_wrapper, std::tuple, std::packaged_task, ...

    To give you an example I'll show you how a reference_wrapper might be implemented with respect to variadic templates:

    template
    class reference_wrapper
    {
        T *ptr;
    public:
        explicit reference_wrapper(T& thing) : ptr(&thing) {}
        explicit reference_wrapper(T&&     ) = delete;
    
        operator T&() const {return *ptr;}
    
        template
        decltype( declval()(declval()...) )
        operator()(Args&&... args) const
        {
            return (*ptr)(forward(args)...);
        }
    };
    

    This is not perfectly conforming to the standard draft but it is supposed to be compilable with little modification. It demonstrates multiple C++0x features:

    • deleted functions (disabling the constructor for rvalues)
    • rvalue references (detecting rvalue arguments to the constructor, perfect forwarding)
    • type deduction via decltype
    • standard library function template declval to create objects for the purpose of building an expression for decltype (GCC does not yet offer this function template. You have to write it yourself)
    • variadic templates (accepting an arbitrary number of parameters)

    The purpose of the variadic member template is to forward arguments to the object referred to by ptr. This should work in case T is a function pointer type or a class type with overloaded function call operator.

    cheers! s

提交回复
热议问题