Thanks for using Compiler Explorer
Sponsors
Jakt
C++
Ada
Analysis
Android Java
Android Kotlin
Assembly
C
C3
Carbon
C++ (Circle)
CIRCT
Clean
CMake
CMakeScript
COBOL
C++ for OpenCL
MLIR
Cppx
Cppx-Blue
Cppx-Gold
Cpp2-cppfront
Crystal
C#
CUDA C++
D
Dart
Elixir
Erlang
Fortran
F#
GLSL
Go
Haskell
HLSL
Hook
Hylo
IL
ispc
Java
Julia
Kotlin
LLVM IR
LLVM MIR
Modula-2
Nim
Objective-C
Objective-C++
OCaml
Odin
OpenCL C
Pascal
Pony
Python
Racket
Ruby
Rust
Snowball
Scala
Slang
Solidity
Spice
SPIR-V
Swift
LLVM TableGen
Toit
TypeScript Native
V
Vala
Visual Basic
Vyper
WASM
Zig
Javascript
GIMPLE
Ygen
cppx source #1
Output
Compile to binary object
Link to binary
Execute the code
Intel asm syntax
Demangle identifiers
Verbose demangling
Filters
Unused labels
Library functions
Directives
Comments
Horizontal whitespace
Debug intrinsics
Compiler
CppCon 2017
CppCon 2018
p1240r1
p1240r2 trunk
p2320 trunk
Options
Source code
//==================================================================== // Library code: implementing the metaclass (once) $class interface { constexpr { compiler.require($interface.variables().empty(), "interfaces may not contain data"); for... (auto f : $interface.functions()) { compiler.require(!f.is_copy() && !f.is_move(), "interfaces may not copy or move; consider a" " virtual clone() instead"); if (!f.has_access()) f.make_public(); compiler.require(f.is_public(), "interface functions must be public"); f.make_pure_virtual(); } } virtual ~interface() noexcept { } }; //==================================================================== // User code: using the metaclass to write a type (many times) interface Shape { int area() const; void scale_by(double factor); }; // try putting any of these lines into Shape to see "interface" rules // enforced => using the metaclass name to declare intent makes // this code more robust to such changes under maintenance // // int i; // error: interfaces may not contain data // private: void g(); // error: interface functions must be public // Shape(const Shape&); // error: interfaces may not copy or move; // // consider a virtual clone() instead // Godbolt.org note: Click the "triangle ! icon" to see the output constexpr { compiler.debug($Shape); } //==================================================================== // And then continue to use it as "just a class" as always... this is // normal code just as if we'd written Shape not using a metaclass class Circle : public Shape { public: int area() const override { return 1; } void scale_by(double factor) override { } }; #include <memory> int main() { std::unique_ptr<Shape> shape = std::make_unique<Circle>(); shape->area(); }
Become a Patron
Sponsor on GitHub
Donate via PayPal
Source on GitHub
Mailing list
Installed libraries
Wiki
Report an issue
How it works
Contact the author
CE on Mastodon
CE on Bluesky
About the author
Statistics
Changelog
Version tree