如何使用可变参数模板初始化指针?

How to initialize the pointer with the variadic-template?

如何使用可变参数模板正确分配指针。

我试过这个:

#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;
}

但是没用。

您可以通过引用传递可变参数:

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

或使用 std::ref

reference_wrapper 传递给参数
#include <functional>  // std::ref

int main()
{
    bool* a1, * a2;
    init(std::ref(a1), std::ref(a2));
    //   ^^^^^^^^^^^^  ^^^^^^^^^^^^
}

或者,如果您可以访问 you can use fold expression,例如:

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

正如评论中提到的@LightnessRacesinOrbit,args 经历了赋值,而不是初始化。