mardi 1 mai 2018

Implementing a move constructor of a tagged union

I implemented a tagged union using a class containing an anonymous union and a tag:

class LogFile
{
  public:
    LogFile(std::ostream& stdStream);
    LogFile(std::ofstream fileStream);
    LogFile(LogFile&& logFile);
    ~LogFile();

    std::ostream& getStream();

  private:
    enum { STD_STREAM, FILE_STREAM } streamType_;
    union
    {
        std::ostream *stdStream_;
        std::ofstream fileStream_;
    };
};

I have trouble implementing the move constructor. In the overloaded "normal" constructors I know which union member to initialize:

LogFile::LogFile(std::ofstream fileStream)
: streamType_(FILE_STREAM), fileStream_(std::move(fileStream))
{
}

But in the move constructor, how do I know which of stdStream_ or fileStream_ I have to initialize. I can't check the value of streamType_ in the initializer list.

Aucun commentaire:

Enregistrer un commentaire