samedi 5 août 2017

How to create a private static const string when using the pimpl idiom

Background

I have been learning how to implement the pimpl idiom using the newer c++11 method described by Herb Sutter at this page: http://ift.tt/2riSZ0i

I'm trying to modify this example by adding a member variable to the private implementation, specifically a std::string (although a char* has the same issue).

Problem

This seems to be impossible due to the use of a static const non-integral type. In-class initialization can only be done for integral types, but because it is static it can't be initialized in the constructor either.

A solution to this problem is to declare the private variable in the header file, and initialize it in the implementation, as shown here: C++ static constant string (class member)

However, this solution does not work for me because it breaks the encapsulation I'm trying to achieve through the pimpl idiom.

Question

How can I hide a non-integral static const variable within the hidden inner class when using the pimpl idiom?

Example

Here is the simplest (incorrect) example I could come up with demonstrating the problem:

Widget.h:

#ifndef WIDGET_H_
#define WIDGET_H_

#include <memory>

class Widget {
public:
    Widget();
    ~Widget();
private:
    class Impl;
    std::unique_ptr<Impl> pimpl;
};

#endif

Widget.cpp:

#include "Widget.h"
#include <string>

class Widget::Impl {
public:
    static const std::string TEST = "test";

    Impl() { };
    ~Impl() { };
};

Widget::Widget() : pimpl(new Impl()) { }
Widget::~Widget() { }

Compilation command:

g++ -std=c++11 -Wall -c -o Widget.o ./Widget.cpp

Note that this example fails to compile because the variable TEST cannot be assigned at declaration due to it not being an integral type; however, because it is static this is required. This seems to imply that it cannot be done.

I've been searching for previous questions/answers to this all afternoon, but could not find any that propose a solution that preserves the information-hiding property of the pimpl idiom.

Aucun commentaire:

Enregistrer un commentaire