Search code examples
c++pointerstemplatesc++17variadic-templates

How to initialize the pointer with the variadic-template?


How to correctly assign a pointer with the variadic template.

I tried this:

#include <iostream>
using namespace std;

void init() { cerr << "EMPTY" << endl; }

template <typename A, typename ...B> void init(A argHead, B... argTail) 
{
    argHead = new bool;
    *(argHead) = true;
    init(argTail...);
}

int main(int argc, char *argv[]) 
{
    bool *a1,*a2;
    init(a1,a2);
    std::cout << (*a1) << " " << (*a2) << std::endl;

    return 0;
}

But it doesn't work.


Solution

  • You can pass the variadic-args by reference:

    template <typename A, typename ...B> void init(A& argHead, B&... argTail)
    //                                             ^^          ^^^^^^^^^^^^^^
    {
        argHead = new bool{true};
        init(argTail...);
    }
    

    Or pass the reference_wrapper to the args using std::ref

    #include <functional>  // std::ref
    
    int main()
    {
        bool* a1, * a2;
        init(std::ref(a1), std::ref(a2));
        //   ^^^^^^^^^^^^  ^^^^^^^^^^^^
    }
    

    Alternatively, if you have access to you can use fold expression like:

    template <typename... Args> void init(Args&... args) 
    {
        ((args = new bool{ true }), ...);
    }
    

    As @LightnessRacesinOrbit mentioned in the comments, the args undergoes assignment, not the initialization.