Skip to content

Commit

Permalink
✨ add integral constant
Browse files Browse the repository at this point in the history
  • Loading branch information
zie87 committed Oct 5, 2023
1 parent 025bc5d commit 40588e3
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
27 changes: 27 additions & 0 deletions include/zll/meta/integral_constant.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#ifndef ZLL_META_INTEGRALCONSTANT_HPP
#define ZLL_META_INTEGRALCONSTANT_HPP

namespace zll {
namespace meta {

template <typename T, T VALUE_V>
struct integral_constant {
typedef T value_type;
typedef integral_constant<T, VALUE_V> type;

static const value_type value = VALUE_V;

operator value_type() const { return VALUE_V; }
value_type operator()() const { return VALUE_V; }
};

template <bool BOOL_V>
struct bool_constant : integral_constant<bool, BOOL_V> {};

typedef bool_constant<true> true_type;
typedef bool_constant<false> false_type;

} // namespace meta
} // namespace zll

#endif // ZLL_META_INTEGRALCONSTANT_HPP
2 changes: 1 addition & 1 deletion tests/unit_tests/meson.build
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

unit_tests_srcs = [
'meta/integral_constant_tests.cpp',
'main.cpp',
]

Expand All @@ -9,7 +10,6 @@ unit_tests_exec = executable(
unit_tests_srcs,
include_directories: unit_tests_inc_dir,
dependencies: [utest_dep, dis_dep],
override_options: ['cpp_std=c++20', 'warning_level=3'],
)

test('zll-unit-tests', unit_tests_exec, suite: 'dis')
33 changes: 33 additions & 0 deletions tests/unit_tests/meta/integral_constant_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include "zll/meta/integral_constant.hpp"
#include "zll/debug/static_assert.hpp"

#include <utest.h>

UTEST(meta_integral_constant, int_constant) {
typedef zll::meta::integral_constant<int, 2> two_t;

const two_t two = two_t();
ASSERT_EQ(two_t::value, 2);
ASSERT_EQ(two(), 2);
const int val = two;

ASSERT_EQ(val, 2);
ZLL_STATIC_ASSERT((two_t::value == 2));
}

UTEST(meta_integral_constant, bool_constant) {
{
const zll::meta::true_type true_v;
ASSERT_TRUE((zll::meta::true_type::value));
ASSERT_TRUE(true_v);
ASSERT_TRUE(true_v());
ZLL_STATIC_ASSERT((zll::meta::true_type::value));
}
{
const zll::meta::false_type false_v;
ASSERT_FALSE((zll::meta::false_type::value));
ASSERT_FALSE(false_v);
ASSERT_FALSE(false_v());
ZLL_STATIC_ASSERT(!(zll::meta::false_type::value));
}
}

0 comments on commit 40588e3

Please sign in to comment.