I've decided to implement Python's any
in C++. I've gone about this using templates to allow multiple types of data to be passed, instead of overloading the function multiple times. This is my first time using templates so I would really like feedback about my usage of them. I'm also fairly new with references and pointers, so I would like some criticism about my use of them as well. Of course, anything else is on the table and appreciated.
While writing this program, I realized std::any_of
existed. So yes, I do know there's already a built-in method for this.
any.hpp
#ifndef ANY_HPP_INCLUDED
#define ANY_HPP_INCLUDED
/**
* @author Ben Antonellis
**/
#include <vector>
#include <iostream>
/**
* Returns True if any of the elements meet the callback functions parameters.
*
* @param elements - A list of elements.
* @param callback - Callback function to invoke on each element.
*
* @return bool - True if parameters are met, False otherwise.
**/
template <typename List, typename Function>
bool any(List &elements, Function *callback) {
for (auto element : elements) {
if (callback(element)) {
return true;
}
}
return false;
}
#endif
And here's how I'm testing this function:
main.cpp
/**
* @author Ben Antonellis
**/
#include "Any.hpp"
int main() {
std::vector<double> doubleElements = {-1.0, -2.0, -3.0};
std::vector<std::string> stringElements = {"Hello", "Goodbye", "Testing 123"};
auto doubleFunc = [] (double number) {
return number < 0;
};
auto stringFunc = [] (std::string string) {
return string.length() >= 5;
};
/* Test Any Implementation */
if (any(doubleElements, *doubleFunc)) {
std::cout << "(any) Double Success." << std::endl;
}
if (any(stringElements, *stringFunc)) {
std::cout << "(any) String Success." << std::endl;
}
return 0;
}
If you would like to compile and run, below is the script I'm using to compile and run this program.
run.sh
# Compile c++ program to .o file #
g++ -std=gnu++2a -c main.cpp # gnu++2a = Working draft for ISO C++ 2020 with GNU extensions #
# Compile .o file to executable #
g++ main.o -o app
# Run the executable #
./app
# Delete executable and .o files after running #
rm app main.o