Skip to content

Instantly share code, notes, and snippets.

@Cypher1
Last active July 21, 2022 10:24
Show Gist options
  • Save Cypher1/0daa19f9786edb816fb69102325383e6 to your computer and use it in GitHub Desktop.
Save Cypher1/0daa19f9786edb816fb69102325383e6 to your computer and use it in GitHub Desktop.
Print and count ints
#include <iostream>
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <numeric>
// give the two templates
// need to write the variadic template
// need to explain what is going on.
/*
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
out << "[";
if(v.begin() != v.end()) {
out << *v.begin();
std::for_each(v.begin()++, v.end(), [&out](const T& t){ out << " " << t; });
}
out << "]";
return out;
}*/
template <typename T>
constexpr bool printIfWholeNumber(const T&,
typename std::enable_if<!std::is_arithmetic<T>::value,
T>::type* =0) {
// std::cout << "FAILED: " << t << std::endl;
return false;
}
template <typename T>
constexpr bool printIfWholeNumber(const T& i,
typename std::enable_if<std::is_arithmetic<T>::value, T>::type* =0) {
if(std::trunc(i) == i) {
std::cout << i;
return true;
}
return false;
}
template <typename T>
constexpr unsigned int printAndCountWholeNumbers(const T& d) {
if (printIfWholeNumber(d)) {
std::cout << " ";
return 1;
}
return 0;
}
template <typename T>
constexpr unsigned int printAndCountWholeNumbers(const std::vector<T>& vec) {
return std::accumulate(vec.begin(), vec.end(), 0U, [](const unsigned int& t, const T& v){
if(printAndCountWholeNumbers(v)) {
return t+1;
} else {
return t;
}
});
}
// disclaimer: this is bad. We'll talk about perfect forwarding later
template <typename HEAD, typename... TAIL>
constexpr unsigned int printAndCountWholeNumbers(HEAD head, TAIL... tail) {
return printAndCountWholeNumbers(head)+printAndCountWholeNumbers(tail...);
}
int main() {
printIfWholeNumber(std::string("Hello world!"));
printIfWholeNumber(2.0f);
printIfWholeNumber(std::vector<double>());
// why does 7.0 not get printed?
auto c = printAndCountWholeNumbers(1,2.5,3,4.5,5.5,6,7.0,-5,"2");
std::cout << "count = " << c << std::endl;
// why does 32 print this time?
std::vector<double> d = {1.2,32.0,3.2,5.30,5.4,6,-5};
auto dc = printAndCountWholeNumbers(d);
std::cout << "count = " << dc << std::endl;
std::vector<unsigned int> vui = { 65,343,21,3};
dc = printAndCountWholeNumbers(vui);
std::cout << "count = " << dc << std::endl;
}
@venik
Copy link

venik commented Jul 13, 2022

was thinking for about 10 mins and didnt crack why 7.0 not get printed... but it does
https://godbolt.org/z/7dGG768fE

@Cypher1
Copy link
Author

Cypher1 commented Jul 21, 2022

Interesting... You're right, though I don't remember the context of this gist (at all) so I'm not sure that I actually believed the content of the comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment