Skip to content

Instantly share code, notes, and snippets.

@axx
Last active April 22, 2019 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axx/4160b06a0f3e2832c1b2c5087870db4a to your computer and use it in GitHub Desktop.
Save axx/4160b06a0f3e2832c1b2c5087870db4a to your computer and use it in GitHub Desktop.
A test for C++17 fold expression
// Filename: main.cpp
// To compile: g++-8 -std=c++17 main.cpp
#include <iostream>
#include <type_traits>
#include <tuple>
template <typename T, typename Tuple>
struct has_type;
template <typename T, typename... Us>
struct has_type<T, std::tuple<Us...>> : std::disjunction<std::is_same<T, Us>...> {};
template<typename T>
struct enable_cache {
enable_cache(T t) :value(t) {}
T value;
};
template<typename T>
bool need_cache(T&& t) {
if constexpr(std::is_same_v<T, enable_cache<bool>>) {
return t.value;
}
else {
return false;
}
}
struct log_t {};
template<typename... AP>
void do_something(AP&&... ap)
{
if constexpr(has_type<enable_cache<bool>, std::tuple<std::decay_t<AP>...>>::value) {
bool b = true;
((b&&(b = need_cache(std::forward<AP>(ap))), false),...);
if (b) {
std::cout << "need cache" << std::endl;
}
else {
std::cout << "skip cache" << std::endl;
}
}
else {
std::cout << "does not have type enable_cache" << std::endl;
}
std::cout << "==========" << std::endl;
}
int main()
{
std::cout << "do_something(log_t{})" << std::endl;
do_something(log_t{});
std::cout << "do_something(enable_cache{ false })" << std::endl;
do_something(enable_cache{ false });
std::cout << "do_something(enable_cache{ true })" << std::endl;
do_something(enable_cache{ true });
std::cout << "do_something(log_t{}, enable_cache{ false })" << std::endl;
do_something(log_t{}, enable_cache{ false });
std::cout << "do_something(log_t{}, enable_cache{ true })" << std::endl;
do_something(log_t{}, enable_cache{ true });
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment