GithubHelp home page GithubHelp logo

contour-terminal / boxed-cpp Goto Github PK

View Code? Open in Web Editor NEW
9.0 3.0 2.0 71 KB

Boxing primitive types in C++

License: Apache License 2.0

CMake 39.12% C++ 60.88%
typesystem cplusplus-17 header-only code-quality

boxed-cpp's Introduction

C++ primitive type boxing

This is a small header-only library for easing primitive type boxing in C++. Primary goal of the library is to make it easy to avoid code with easily swappable parameters clang-tidy:bugprone-easily-swappable-parameters.

Overview on the topic: C++ Weekly With Jason Turner

library is created to aid code health in Contour Terminal Emulator.

This header can be simply copied into a project or used via CMake builtin functions, such as FetchContent.

Simple usage

Example of creation boxed structures and usage

#include <boxed-cpp/boxed.hpp>

// Create unique structures

using Speed = boxed::boxed<double>;
using Permittivity = boxed::boxed<double>;
using Permeability = boxed::boxed<double>;

int main()
{
    auto wave_speed = [](Permittivity epsilon, Permeability mu) -> Speed
    {
        return Speed(1.0 / std::sqrt(unbox(epsilon) * unbox(mu)));
    };
    auto vacuum_permittivity = Permittivity(8.85418781762039e-12);
    auto pi = 3.14159265358979323846;
    auto vacuum_permeability = Permeability(4 * pi * 1e-7);

    auto speed = wave_speed(vacuum_permittivity, vacuum_permeability);
    // speed == Speed(299792458.0);

    // Wrong order of parameters will result in compilation error
    // wave_speed(vacuum_permeability, vacuum_permittivity);
}

You can create boxed types in the following way:

using boxed_type = boxed::boxed<int>;

struct Tag{};
using boxed_type_with_custom_tag = boxed::boxed<int,Tag>;

When you need to get value from a boxed type, you need to unbox it, use get method, or cast it into another type with as.

//unbox in declared type. double in this case
auto speed_value_native = unbox(speed_of_light); // identical to speed_of_light.get();
//unbox into float type
auto speed_value_float = unbox<float>(speed_of_light); // identical to speed_of_light.as<float>();
// unbox into int type
auto speed_value_int = unbox<int>(speed_of_light); // identical to speed_of_light.as<int>();

You can also evaluate expressions with boxed types without the need of unboxing them

auto speed_of_light = Speed(299792458.0);
auto value = speed_of_light * 2.0; // type of value is Speed

// boxed value will be automatically unboxed into type that was boxed, in this case double
double value_d = speed_of_light * 2.0;

Another examples

You can create functions that will automatically adjust order of parameters. godbolt

using rho_type = boxed::boxed<double>;
using theta_type = boxed::boxed<double>;
using phi_type = boxed::boxed<double>;

template <typename... F> struct overload : F... {
  using F::operator()...;
};

template <typename... Ts> overload(Ts...) -> overload<Ts...>;

template <typename... Ts> struct Wrap {
  overload<Ts...> func_wrap;

  Wrap(Ts... funcs) : func_wrap(funcs...) {}

  template <typename... Args> auto operator()(Args... args) {
    return (func_wrap(args) * ...);
  }
};

auto x_coord = Wrap([](rho_type rho) { return unbox(rho); },
                    [](theta_type theta) { return sin(unbox(theta)); },
                    [](phi_type phi) { return cos(unbox(phi)); });

int main() {
  rho_type rho{1.0};
  theta_type theta{3.14 / 3.0};
  phi_type phi{3.14 / 2.0};

  x_coord(rho, theta, phi) == x_coord(phi, theta, rho);
  x_coord(rho, theta, phi) == x_coord(theta, phi, rho);
}

Or using another approach: godbolt

using rho_type = boxed::boxed<double>;
using theta_type = boxed::boxed<double>;
using phi_type = boxed::boxed<double>;

template <typename Func, typename... Tuple> struct Wrap_with_tuple {
  using type_order = std::tuple<Tuple...>;

  Wrap_with_tuple(Func f, type_order s) : _func(f), _order(s) {};

  template <typename... F> decltype(auto) operator()(F... args) {
    auto arg_tuple = std::make_tuple(args...);
    auto ints = std::make_index_sequence<sizeof...(args)>{};
    return make_call(arg_tuple, ints);
  }

  template <typename call_tuple, typename T, T... ints>
  decltype(auto) make_call(call_tuple arg_tuple,
                           std::integer_sequence<T, ints...> int_seq) {
    return _func(
        std::get<std::decay_t<decltype(std::get<ints>(_order))>>(arg_tuple)...);
  }

  Func _func;
  type_order _order;
};

auto x_coord = Wrap_with_tuple(
    [](rho_type rho, theta_type theta, phi_type phi) {
      return unbox(rho) * sin(unbox(theta)) * cos(unbox(phi));
    },
    std::make_tuple(rho_type{}, theta_type{}, phi_type{}));

int main() {
  rho_type rho{1.0};
  theta_type theta{3.14 / 3.0};
  phi_type phi{3.14 / 2.0};

  x_coord(rho, theta, phi) == x_coord(phi, theta, rho);
  x_coord(rho, theta, phi) == x_coord(theta, phi, rho);
}

License

boxed-cpp
=========

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

boxed-cpp's People

Contributors

christianparpart avatar topazus avatar yaraslaut avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

boxed-cpp's Issues

Adding the Apache-2.0 license file

I opened a Red Hat Bugzilla ticket to introduce boxed-cpp into Fedora. I ignored the missing of the license file in the project, which the header file showed the Apache-2.0 license.

/**
* This file is part of the "libterminal" project
* Copyright (c) 2020-2021 Christian Parpart <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

Ref: https://bugzilla.redhat.com/show_bug.cgi?id=2245909

CMake improvement

  • Use install() to specify files that needed to be installed for boxed-cpp.
  • It also can generate config files with configure_package_config_file() and write_basic_package_version_file(), so that other projects can find and use boxed-cpp.

The above improvements will facilitate the packaging of contour-terminal, since boxed-cpp is one of the dependencies of contour-terminal.

Ref:

  1. https://cmake.org/cmake/help/latest/command/install.html
  2. https://cmake.org/cmake/help/latest/module/CMakePackageConfigHelpers.html
  3. https://github.com/contour-terminal/contour/blob/76f172e01b16bd024793f133edf65b866e2f0064/cmake/ContourThirdParties.cmake#L130-L131

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.