Code Monkey home page Code Monkey logo

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
namespace tags { struct Speed{}; struct Permittivity{}; struct Permeability{}; }

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


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);
}

When you need to get value from boxed type, you need to unbox it

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

You can also evaluate expressions with boxed types without the need of unboxing them if explicitly declare the resulted type

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;

More advanced usage

You can forget about the order of parameters in your code. Complete code see: godbolt

namespace Tag{ struct Rho{}; struct Theta{}; struct Phi{};}

using rho_type = boxed::boxed<double,Tag::Rho>;
using theta_type = boxed::boxed<double,Tag::Theta>;
using phi_type = boxed::boxed<double,Tag::Phi>;


template<typename ...T>
struct Wrap{};

template<typename T, typename ...Rest>
struct Wrap<T, Rest ...>
{

    constexpr static inline std::size_t n = 1 + sizeof...(Rest);
    using fun_type = std::function<double(T)>;
    Wrap(fun_type&& first,  std::function<double(Rest)>&& ...rest)
        : first(std::forward<fun_type>(first))
        , rest(std::forward<std::function<double(Rest)>>(rest)...)
    {}

    const fun_type first;
    Wrap<Rest...> rest;

    auto operator()(T v)
    {
        return first(v);
    }

    template<typename F>
    requires (!std::is_same_v<T,F>)
    decltype(auto) operator()(F v)
    {
        return rest(v);
    }


    template<typename ...Args>
    requires (!std::derived_from<all_different<typename std::decay<Args>::type...>, std::false_type>)
    decltype(auto) operator()(Args &&... args)
    {
        static_assert( (sizeof...(Args) == n) );
        return ( operator()(std::forward<Args>(args)) * ... );
    }
};

auto x_coord = Wrap<rho_type,theta_type,phi_type>{
                                                  [](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};

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

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

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.