我正在嘗試將一些 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()方法版本。
uj5u.com熱心網友回復:
有 3 種不同的方式來接受可變數量的引數。
首先,C 風格的可變引數。你可能不想要這個。
其次,C 可變引數模板。如果一切都是相同的型別,可能會矯枉過正。
最后,std::initializer_list如果資料是常量,則類似于 a 。否則,只是一個std::vector.
std::string AstPrinter::parenthesize(std::string name, std::vector<Expr<std::string>> exprs)
在呼叫站點,執行printer.parenthesize("foo", {Expr0, Expr1, Expr2});。注意額外的{}.
這是解決您的問題的最簡單方法。
uj5u.com熱心網友回復:
在 C 17 及更高版本中,vector如果使用折疊運算式,則可以避免將可變引數復制到 a 中,例如:
template <typename... Args>
std::string AstPrinter::parenthesize(const std::string& name, const Args&... exprs)
{
return "("
name
(
(" " exprs.accept(this)) ... // <-- here
)
")";
}
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/312587.html
