Пространство имен или класс, что лучше для инкапсуляции только членов функции

Итак, допустим, у меня есть несколько функций для работы с открытием/закрытием файлов.

Лучше ли сделать класс со всеми этими функциями, объявленными статически... или просто поместить "публичную" функцию в заголовочный файл пространства имен "file", а остальные "детали реализации" поместить в файл .cc?

Ниже приведены примеры кода.

Для пространства имен он немного длинноват, так как я хочу сделать его как можно более понятным.

СПАСИБО!!!


реализация класса

Заголовок:

#ifndef FILE_H
#define FILE_H

#include <iostream>
#include <fstream>

include "common.h"

enum Errorcode {
    FILE_CANNOT_OPEN,
    FILE_CANNOT_CLOSE
};

class file {

public:
    static common::Lines toLines(std::string filename);

private:
    static void err(Errorcode e, std::string msg);
    static void toLines(std::ifstream &ifs, common::Lines &lines);

};

#endif

.cc файл:

/*just the implementation details of above class.*/

реализация пространства имен

Заголовок:

#ifndef FILE_H
#define FILE_H

#include <iostream>
#include <fstream>

#include "common.h"

namespace file {

common::Lines toLines(std::string filename);

}

#endif    

.cc файл:

namespace file {

enum Errorcode {
    FILE_CANNOT_OPEN,
    FILE_CANNOT_CLOSE
};

void err(Errorcode e, std::string msg);
void toLines(std::ifstream& ifs, common::Lines &lines);

common::Lines toLines(std::string filename)
{
    std::vector<std::string> lines;

    try {
        std::ifstream ifs(filename.c_str());
        if (ifs.fail()) throw FILE_CANNOT_OPEN;

        toLines(ifs, lines);

        ifs.close();
        if (ifs.fail()) throw FILE_CANNOT_CLOSE;
    }
    catch (Errorcode e) {
        err(e, filename);
    }

    return lines;
}

void err(Errorcode e, std::string msg)
{
    switch (e) {
        default:
            std::cerr << "Unknown error.\n";
            break;
        case FILE_CANNOT_OPEN:          
            std::cerr << "file \"" << msg   
                << "\" could not be opened.\n"; 
            break;
        case FILE_CANNOT_CLOSE:         
            std::cerr << "file \"" << msg   
                << "\" could not be closed.\n"; 
            break;
    }
    std::exit(-1);
}

void toLines(std::ifstream& ifs, common::Lines &lines)
{
    std::string line;

    while(std::getline(ifs, line)) {
        lines.push_back(line);
    }

    ifs.clear();    // clear error bit set by getline()
}

}                    
9
задан Jimmy Lu 30 January 2012 в 05:01
поделиться