【问题标题】:How can I use the same function template to save 3 different arrays to 3 different files?如何使用相同的函数模板将 3 个不同的数组保存到 3 个不同的文件中?
【发布时间】:2017-09-28 00:28:09
【问题描述】:

如何使用同一个函数模板将 3 个不同的数组保存到 3 个不同的文件中? (每个文件一个数组)

数组类型为intfloatchar

我得到的最接近的是以下代码:

template <typename T>
    void saveToTextFile(T *arr, const int size)
    {
    ofstream outFile("arraytextfile.txt", ios::out);`

        for(unsigned int i = 0; i < size; ++i)
        {
            outFile << arr[i] << ' ';
        }// end for

        outFile << endl;

        outFile.close();
    } 

这当然会在第一次调用时创建一个新的文本文件,然后在再次打开时截断该文件。 我需要调用此模板 3 次不同的时间,并让它每次都将数据保存到一个新文件中。每个文件应包含不同的数组。

【问题讨论】:

  • 是否将要创建的文件的名称作为附加参数传递给此函数,是否太明显的解决方案?
  • 这正是我正在寻找的解决方案!谢谢!

标签: c++ arrays templates file-io


【解决方案1】:

如果你确定你只用三种不同的类型调用这个函数,并且你至少使用 C++11,一个简单(但不是很优雅)的解决方案是使用类型特征并检查类型;像

std::ofstream outFile(
   std::is_same<T, char>::value
      ? "file-char.txt"
      : (std::is_same<T, int>::value
         ? "file-int.txt"
         : "file-double.txt"), std::ios::out);

如果你不能使用 C++11 或更新版本,你可以用下面的东西模拟std::is_same

template <typename, typename>
struct isSame
 { static const bool value = false; };

template <typename T>
struct isSame<T, T>
 { static const bool value = true; };

但对于更通用的解决方案,您可以使用typeid();举例

std::string  fName = "file-";

fName += typeid(*arr).name();
fName += ".txt";

std::ofstream outFile(fName, std::ios::out);

但要考虑到 typeid() 给出的 name() 取决于实现。

【讨论】:

    【解决方案2】:

    你为什么不通过参数传递filePath,使用pointer

     void saveToTextFile(T *arr, const int size, const char *outputFilePath) {
         ofstream outFile(outputFilePath , ios::out);`
     }
    

    您可以将 filePath 传递给您的函数,例如:

    const char * location = "a/c/d.text".c_str();
    saveToTextFile(arr, 5, location) // or for short 
    saveToTextFile(arr, 5,"a/c/d.text".c_str())
    

    【讨论】:

    • "a/c/d.text".c_str(); 这里有一个错误。 "a/c/d.text" 是一个const char 数组,而不是std::string,所以不仅没有c_str() 可以调用,也没有理由调用任何东西。转换为const char * 是免费的。
    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 2020-02-12
    • 2013-05-26
    • 2014-04-16
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多