online compiler and debugger for c/c++

code. compile. run. debug. share.
Source Code    Language
#include <iostream> #include <memory> #include <string> #include <type_traits> struct Writer // Toy example { template <typename T> void operator()(const T& v) {std::cout << v << ", ";} }; struct ArrayWriter // Toy example { ArrayWriter() {std::cout << "[";} ~ArrayWriter() noexcept {std::cout << "], ";} template <typename T> void operator()(const T& v) {std::cout << v << ", ";} }; // "Regular" shared_ptr template <typename T> void serialize(Writer& writer, const std::shared_ptr<T> ptr) { static_assert(!std::is_array_v<T>, "shared_ptr<T[]> not supported: size unknowable"); if (ptr) writer(*ptr); else writer("null"); } // shared_ptr holding an array of known size template <typename T, std::size_t N> void serialize(Writer& writer, const std::shared_ptr<T[N]> ptr) { if (ptr) { ArrayWriter arrayWriter; static constexpr auto size = N; for (std::size_t i=0; i<size; ++i) arrayWriter(ptr[i]); } else writer("null"); } int main() { Writer writer; std::shared_ptr<std::string> s{new std::string{"Hello"}}; std::shared_ptr<int[3]> n{new int[3]}; // Error prone! std::shared_ptr<float[]> x{new float[5]}; // Error prone! n[0] = 1; n[1] = 2; n[2] = 3; serialize(writer, s); // Outputs Hello, serialize(writer, n); // Outputs [1, 2, 3, ], // serialize(writer, x); // static assertion failure return 0; }

Compiling Program...

Command line arguments:
Standard Input: Interactive Console Text
×

                

                

Program is not being debugged. Click "Debug" button to start program in debug mode.

#FunctionFile:Line
VariableValue
RegisterValue
ExpressionValue