Created
June 28, 2024 22:12
-
-
Save tcbrindle/5867211b8d34cc332d91846c1d54f235 to your computer and use it in GitHub Desktop.
Minimal demo of the pimpl idiom using C++20 modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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_; | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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