簡體   English   中英

如何使用模板根據 class 中的參數設置數組大小

[英]How to have array size depending on parameter in class using template

我有一個由 Q 元組組成的圖,其中 Q 為 3 或 6。圖中的節點分別建模為typedef std::array<int,3> NODEtypedef std::array<int,6> NODE . 為了更靈活,我使用了模板 class

template <int Q>
class DARP
{
// some attributes
    int capacity = Q;
    typedef std::array<int,Q> NODE;
    NODE depot;
    void create_nodes();
};

但是,以下實現會導致錯誤。

template <int Q>
void DARP<Q>::create_nodes()
{
    if (capacity == 3)
        depot = {0,0,0};
    else
        depot = {0,0,0,0,0,0};  
}

這可以通過

template <int Q>
void DARP<Q>::create_nodes()
{
    for (int i=0; i<Q; i++)
    {
        depot[i] = 0;
    }
}

但是當我想創建像{0,1,4,8,9,10}這樣更復雜的節點時,能夠以這種“短”形式編寫它會派上用場。 有沒有辦法更優雅地處理這個問題?

您可以將Constexpr If (C++17 起) 與模板參數Q一起使用:

if constexpr (Q==3)
    depot = {0,0,0};
else
    depot = {0,0,0,0,0,0};  

根據條件值, statement-truestatement-false將被丟棄,不會導致錯誤。

在 C++17 之前,您可以將create_nodes指定為:

template <>
void DARP<3>::create_nodes()
{
    depot = {0,0,0};
}
template <>
void DARP<6>::create_nodes()
{
    depot = {0,0,0,0,0,0}; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM