Skip to content

Instantly share code, notes, and snippets.

@pr0g
Created July 13, 2020 15:50
Show Gist options
  • Save pr0g/68f30ba4dd2bd207eb00e17a5b82134d to your computer and use it in GitHub Desktop.
Save pr0g/68f30ba4dd2bd207eb00e17a5b82134d to your computer and use it in GitHub Desktop.
C++ constexpr experiments
cmake_minimum_required(VERSION 3.15)
project(constexpr LANGUAGES CXX)
add_executable(${PROJECT_NAME})
target_sources(${PROJECT_NAME} PRIVATE main.cpp)
target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17)
#include <cstddef>
#include <iostream>
#include <memory>
#include <type_traits>
void print_buffer(const std::byte (&buffer)[12])
{
for (int64_t i = 0; i < std::size(buffer); i++) {
printf("%02hhX", buffer[i]);
}
printf("%c", '\n');
}
// <1> - constructor not constexpr, without '{}' when defined
// <2> - constructor not constexpr, with '{}' when defined
// <3> - constructor constexpr, defaulted, without '{}' when defined
// <4> - constructor constexpr, init list, user provided,
// without '{}' when defined
// <5> - constructor constexpr, user provided, without '{}' when defined
// <6> - constructor constexpr, user provided, member initializers, without '{}'
// when defined
// <7> - constructor constexpr, defaulted, member initializers, without '{}'
// when defined
struct vec3
{
vec3() noexcept = default; // <1,2>
// constexpr vec3() noexcept = default; // <3, 7>
// constexpr vec3() : x(0), y(0), z(0) {} // <4>
// constexpr vec3() noexcept {} // <5,6>
float x, y, z; // <1,2,3,4,5>
// float x = 0, y = 0, z = 0; // <6,7>
};
int main(int argc, char** argv)
{
alignas(std::alignment_of<vec3>::value)
std::byte vec3_buffer[sizeof(vec3)] = {
std::byte{0xc0}, std::byte{0xff}, std::byte{0xee}, std::byte{0xc0},
std::byte{0xff}, std::byte{0xee}, std::byte{0xc0}, std::byte{0xff},
std::byte{0xee}, std::byte{0xc0}, std::byte{0xff}, std::byte{0xee}};
// before
print_buffer(vec3_buffer);
// equivalent to 'vec3 v;'
auto v = new (vec3_buffer) vec3; // <1,3,4,5,6,7>
// equivalent to 'vec3 v{};'
// auto v = new (vec3_buffer) vec3{}; // <2>
// after
print_buffer(vec3_buffer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment