如何使用可变参数模板正确分配指针。
我试过这个:
#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));
// ^^^^^^^^^^^^ ^^^^^^^^^^^^
}
或者,如果您有权访问 c++17你可以使用 fold expression 喜欢:
template <typename... Args> void init(Args&... args)
{
((args = new bool{ true }), ...);
}
正如评论中提到的@LightnessRacesinOrbit,args 经历分配,而不是初始化。
关于c++ - 如何使用可变参数模板初始化指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449615/