Skip to content

Commit

Permalink
✨ add enable_if trait
Browse files Browse the repository at this point in the history
  • Loading branch information
zie87 committed Oct 6, 2023
1 parent d1ea09f commit b6053e1
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
24 changes: 24 additions & 0 deletions include/zll/meta/enable_if.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

#ifndef ZLL_META_ENABLEIF_HPP
#define ZLL_META_ENABLEIF_HPP

namespace zll {
namespace meta {

template <bool, typename = void>
struct enable_if {};

template <typename T>
struct enable_if<true, T> {
typedef T type;
};

} // namespace meta
} // namespace zll

#endif // ZLL_META_ENABLEIF_HPP
2 changes: 2 additions & 0 deletions include/zll/type_traits.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#ifndef ZLL_TYPETRAITS_HPP
#define ZLL_TYPETRAITS_HPP

#include "zll/meta/enable_if.hpp"

#include "zll/meta/is_pointer.hpp"
#include "zll/meta/is_same.hpp"

Expand Down
1 change: 1 addition & 0 deletions tests/unit_tests/meson.build
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

unit_tests_srcs = [
'meta/enable_if_tests.cpp',
'meta/integral_constant_tests.cpp',
'meta/is_pointer_tests.cpp',
'meta/is_same_tests.cpp',
Expand Down
36 changes: 36 additions & 0 deletions tests/unit_tests/meta/enable_if_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

#include "zll/meta/enable_if.hpp"
#include "zll/meta/is_same.hpp"
#include "zll/meta/is_pointer.hpp"

#include <utest.h>

namespace test_types {
enum test_values { f = 0, i, p };
}

template <typename T>
typename zll::meta::enable_if<zll::meta::is_same<T, int>::value, test_types::test_values>::type test_function() {
return test_types::i;
}

template <typename T>
typename zll::meta::enable_if<zll::meta::is_same<T, float>::value, test_types::test_values>::type test_function() {
return test_types::f;
}

template <typename T>
typename zll::meta::enable_if<zll::meta::is_pointer<T>::value, test_types::test_values>::type test_function() {
return test_types::p;
}

UTEST(meta_enable_if, sfinae) {
ASSERT_EQ(test_function<int>(), test_types::i);
ASSERT_EQ(test_function<float>(), test_types::f);
ASSERT_EQ(test_function<int*>(), test_types::p);
}

0 comments on commit b6053e1

Please sign in to comment.