簡體   English   中英

需要指針或向量參數

[英]Require pointer or vector argument

我正在定義一個函數,使用模板將2d,1d數組或“點”矢量寫入文件。 編譯時出現錯誤,提示“錯誤C2109:下標需要數組或指針類型”,指示變量“輸入”應為數組或指針類型。 但是我只想實例化以下功能

writers<Array_2d, 3, 4>(my2darray,1);

要么

writers<std::vector<double>, 10, 1>(myvector,1);

Array_2d是一個自定義類,因為我已經定義了允許[] []運算符的Array_2d,因此不應該告訴它是指針還是數組。 我想解決這個問題,因為我想通過定義良好的[] []運算符的類實例化該函數;

template <class item, int DIM1, int DIM2>
void writers(const item & input, int flag=1)
{
    using namespace std;
    ofstream fout;
    if (flag == 0)
    {
        fout.open(filename, std::ios_base::app);
    }
    else
    {
        fout.open(filename);
    }

    fout.setf(std::ios_base::floatfield, std::ios_base::fixed);
    fout.precision(8);
    for (int i = 0; i <DIM1; i++)
    {
        if (DIM2 > 1)
        {
            for (int j = 0; j < DIM2; j++)
            {
                fout.width(17);
                fout << input[i][j];
            }
            fout << "\n";
        }
        else
        {
            fout.width(17);
            fout << input[i];
        }
        fout << endl;
    }
    fout.close();
}

在C ++ 17中, if constexpr ,則可能會執行以下操作:

template <typename Container>
void writers(const Container& input, ofstream& fout)
{
    if constexpr (std::is_same<double, typename Container::value_type>::value) {
        // 1D
        fout.setf(std::ios_base::floatfield, std::ios_base::fixed);
        fout.precision(8);
        for (auto& d : input) {
            fout.width(17);
            fout << d;
        }
        fout << endl;
    } else {
        // 2D (or 3D, ...)
        for (const auto& inner : input) {
            writers(inner, fout);
        }
    }
}

暫無
暫無

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

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