Utility¶
The utility header file provides a set of general purpose utilities to simplify common programming tasks. Some of the functions are written to operate during compile-time, while others are written to operate during run-time.
-
namespace utils
Functions
-
template<typename T>
T &get_reference(T &t)¶ Returns a reference to the value or dereferenced pointer.
This function template takes a forwarding reference to a value or pointer. If the argument is a pointer, it returns a reference to the value pointed to by the pointer. Otherwise, it returns the value itself.
- Template Parameters:
T – The type of the argument, deduced automatically.
- Parameters:
t – The value or pointer to be processed.
- Throws:
std::bad_function_call – if the pointer is null.
- Returns:
A reference to the value or dereferenced pointer.
-
template<auto Start, auto End, auto I, typename F>
void constexpr_for(F &&f)¶ Executes a function in a compile-time loop.
This function template executes a given function in a compile-time loop from Start to End with a step of Inc. The function is called with the current index wrapped in an integral constant.
- Template Parameters:
Start – The starting index of the loop.
End – The ending index of the loop.
I – The increment step for each iteration.
F – The type of the function to be called.
- Parameters:
f – The function to be called with the current index.
-
template<typename T>
Usage¶
The following examples demonstrates how to use the utility header file:
get_reference
Output:
1, 1, 1
constexpr_for
// this is rather naive example but it demonstrates how to use the constexpr_for
template <std::size_t N>
struct fibonacci : std::integral_constant<std::size_t,
fibonacci<N-1>::value + fibonacci<N-2>::value> { };
template <>
struct fibonacci<0> : std::integral_constant<std::size_t, 0> {};
template <>
struct fibonacci<1> : std::integral_constant<std::size_t, 1> {};
template <>
struct fibonacci<2> : std::integral_constant<std::size_t, 1> {};
int main() {
constexpr std::size_t n{10};
std::array<std::size_t, n> fib{};
utils::constexpr_for<0, n, 1>([&fib](auto i) {
fib[i] = fibonacci<i>::value;
});
std::cout << fib[99] << std::endl;
}
Output:
3405478146