jeudi 1 novembre 2018

Static const member of private type

I want to initialize a private static member variable of private type.

A minimal working example looks like the following.

error.hpp file

#pragma once

class error {
 public:
  error();
  ~error();

 private:
  struct error_desc {
    int code;
    const char *desc;
    error_desc(int c, const char *d) : code{c}, desc{d} {}
  };

  static const error_desc desc;
};

error.cpp file

#include "pch.h"
#include "error.h"

const error::error_desc desc{0, "Ok"};

error::error() {}

error::~error() {}

Obviously, this results in an error since error::error_desc type is private. Moving error_desc to the public section makes the program to compile fine.

Is there any other way to solve this issue still keeping the type private. The only workaround I can think of is to enclose error::error_desc in a detail namespace and use it in the error class (which of course is not ideal), but I would really like to know a proper solution to this problem.

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire