Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the negative consequences of using typedefs in an implementation file to shorten type signatutures?

I'm doing my first real project in C++, which is a simple CSV parser (in the very early stages right now), and I have the following in a header file:

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);
};

When I want to implement the next function, I found it really annoying to constantly have to type out CsvReader:: before the enums because it made the code so verbose. So instead of having something like this in the implementation

std::tuple<CsvReader::State, CsvReader::Action, bool> next(CsvReader::State s, const char& c) {
  // more usage of CsvReader::
}

I did

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::
}

Except for the fact that I can't call anything else State or Action in the file are there any consequences to doing this? Are there any better solutions?

like image 620
m0meni Avatar asked Jan 05 '23 23:01

m0meni


2 Answers

Instead of this:

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::
}

you can do this:

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::
}

For a separately compiled implementation file there isn't any particular problem with the first approach, but it's awkward and verbose.


By the way, const char& c is not meaningful. And in general, passing by reference to const is not meaningful for types smaller than a pointer, since it causes an address to be passed down at the machine code level. Just use const char c.

like image 84
Cheers and hth. - Alf Avatar answered Jan 25 '23 15:01

Cheers and hth. - Alf


Except for the fact that I can't call anything else State or Action in the file are there any consequences to doing this?

I have done this at my work in numerous files without any problem. I say go for it.

Are there any better solutions?

If you are able to use C++11, you can use using instead of typedef:

using State = CsvReader::State;

It is a more modern idiom. However, the net effect is the same for your use case.

like image 30
R Sahu Avatar answered Jan 25 '23 16:01

R Sahu