C++ template function for arrays, vectors, built in types, STL

后端 未结 2 2037
我寻月下人不归
我寻月下人不归 2021-01-13 07:34

I would like to make a class that has a function that saves the data sent to it, to a text file. The data that can be passed to it can be anything like a std::string<

2条回答
  •  感动是毒
    2021-01-13 08:11

    First, you can either template the class or the functions. Since you want to do arrays as well, you must go with the latter option. Example follows:

    class CMyClass
    {
    public:
        template void SaveData(const T &data);
        template void SaveData(const T (&data)[N]);
        template void SaveData(const T (&data)[N][M]);
        template void SaveData(const std::vector &data);
        template void SaveData(const std::vector > &data);
        void SaveData(const std::string &data);
    };
    

    Once you have defined the functions, the following example shows how you can call them:

    int i;
    int i1[5];
    int i2[5][7];
    std::vector v1;
    std::vector > v2;
    std::string s;
    
    CMyClass saveClass;
    
    saveClass.SaveData(i);
    saveClass.SaveData(i1);
    saveClass.SaveData(i2);
    saveClass.SaveData(v1);
    saveClass.SaveData(v2);
    saveClass.SaveData(s);
    

    Depending on your requirements, you could make the class a singleton and the functions static, omitting the need to instantiate CMyClass at all and simply calling the functions as follows:

    CMyClass::SaveData(i);
    CMyClass::SaveData(i1);
    CMyClass::SaveData(i2);
    CMyClass::SaveData(v1);
    CMyClass::SaveData(v2);
    CMyClass::SaveData(s);
    

    Notes:

    1. The arguments should also be references (i.e. "&data" rather than "data"), so that only the reference is passed rather than performing a copy of the whole container each time you call the function.
    2. I've explicitly declared the functions as public, assuming this is the complete class and its functions will be accessed by another class. By default, the members of a class are private.
    3. Ensure that there is a space between each nested ">".

    Good luck!

提交回复
热议问题