Last active
April 22, 2019 12:14
-
-
Save axx/4160b06a0f3e2832c1b2c5087870db4a to your computer and use it in GitHub Desktop.
A test for C++17 fold expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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