【发布时间】:2021-12-01 12:20:17
【问题描述】:
我正在尝试使一些 Java 代码适应 C++,它们在方法中使用可变参数。在他们的代码中,他们能够将参数作为for 循环中的列表进行迭代。有没有办法在 C++ 中有类似的行为?
我在理解这个概念时遇到了一些麻烦,我觉得我可能对 C++ 中的实现方式有一个基本的误解。我在网上看到了一些类似的代码,似乎将参数列表转换为向量,我尝试在下面实现(注意我需要一个指针向量,以便我可以调用accept()方法的子对象实现)。
std::string AstPrinter::parenthesize(std::string name, Expr<std::string> exprs...)
{
std::vector<Expr<std::string>*> exprVec = { exprs... };
name = "(" + name;
for (Expr<std::string>* expr : exprVec)
{
name += " ";
name += expr->accept(this);
}
name += ")";
return name;
}
代码在第 52 行给出了这些错误:
no instance of constructor "std::vector<_Ty, _Alloc>::vector [with _Ty=Expr<std::string> *, _Alloc=std::allocator<Expr<std::string> *>]" matches the argument list
expected a }
cannot convert from 'initializer list' to 'std::vector<Expr<std::string> *,std::allocator<Expr<std::string> *>>'
我真的不需要它在向量中。我只是想知道如何访问参数列表的成员,以便可以调用他们的 accept() 方法版本。
【问题讨论】:
-
要匹配类型,应该是
{ &exprs... }
标签: c++ templates inheritance variadic-templates variadic-functions