Skip to content

Instantly share code, notes, and snippets.

@tcbrindle
Created June 28, 2024 22:12
Show Gist options
  • Save tcbrindle/5867211b8d34cc332d91846c1d54f235 to your computer and use it in GitHub Desktop.
Save tcbrindle/5867211b8d34cc332d91846c1d54f235 to your computer and use it in GitHub Desktop.
Minimal demo of the pimpl idiom using C++20 modules
cmake_minimum_required(VERSION 3.28)
project(module-pimpl CXX)
set(CMAKE_CXX_EXTENSIONS Off)
add_library(pimpl)
target_compile_features(pimpl PUBLIC cxx_std_20)
target_sources(pimpl PUBLIC
FILE_SET CXX_MODULES
BASE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}
FILES pimpl.cpp
)
target_sources(pimpl PRIVATE pimpl-impl.cpp)
add_executable(test test.cpp)
target_link_libraries(test PRIVATE pimpl)
module;
#include <string>
#include <memory>
module pimpl;
namespace pimpl {
struct TestPrivate {
std::string greeting = "Hello world";
};
Test::Test()
: priv_(std::make_unique<TestPrivate>())
{}
Test::~Test() = default;
const std::string& Test::greeting() const
{
return priv_->greeting;
}
}
module;
#include <memory>
#include <string>
export module pimpl;
namespace pimpl {
class TestPrivate;
export class Test {
public:
explicit Test();
~Test();
const std::string& greeting() const;
private:
std::unique_ptr<TestPrivate> priv_;
};
}
#include <iostream>
import pimpl;
int main()
{
pimpl::Test t;
std::cout << t.greeting() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment