m0m*_*eni 4 c++ enums typedef c++11 c++14
我正在用C++做我的第一个真正的项目,这是一个简单的CSV解析器(现在在很早的阶段),我在头文件中有以下内容:
class CsvReader {
public:
// Actions to commit on each iteration of the CSV parser
enum Action { ADD_CHAR, ADD_FIELD, NONE };
// The possible states for each cell of a CSV
enum State { START, IN_FIELD, IN_QUOTED_FIELD, IN_QUOTED_QUOTE };
// Create the reader from a file
explicit CsvReader(File& f);
// Get a row from the CSV
std::vector<std::string> get_row();
private:
State m_state;
LineReader m_lr;
std::tuple<State, Action, bool> next(State s, const char& c);
};
Run Code Online (Sandbox Code Playgroud)
当我想实现这个next功能时,我发现CsvReader::在枚举之前不断输入它真的很烦人,因为它使代码变得如此冗长.所以不要在实现中有这样的东西
std::tuple<CsvReader::State, CsvReader::Action, bool> next(CsvReader::State s, const char& c) {
// more usage of CsvReader::
}
Run Code Online (Sandbox Code Playgroud)
我做到了
typedef CsvReader::State State;
typedef CsvReader::Action Action;
std::tuple<State, Action, bool> CsvReader::next(State s, const char& c) {
// function signature is much shorter and don't need to use CsvReader::
}
Run Code Online (Sandbox Code Playgroud)
除了我无法调用任何其他内容State或Action文件中的事实,这样做有什么后果吗?还有更好的解决方案吗?
而不是这个:
typedef CsvReader::State State;
typedef CsvReader::Action Action;
std::tuple<State, Action, bool> CsvReader::next(State s, const char& c) {
// function signature is much shorter and don't need to use CsvReader::
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
auto CsvReader::next(State s, const char& c)
-> std::tuple<State, Action, bool>
{
// function signature is much shorter and don't need to use CsvReader::
}
Run Code Online (Sandbox Code Playgroud)
对于单独编译的实现文件,第一种方法没有任何特殊问题,但它很笨拙且冗长.
顺便说一句,const char& c没有意义.通常,通过引用传递const对于小于指针的类型没有意义,因为它会导致地址在机器代码级别向下传递.只是用const char c.