Created
April 14, 2014 00:37
-
-
Save emaxerrno/10608253 to your computer and use it in GitHub Desktop.
template_lazy_closures.cc
This file contains hidden or 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
#include <type_traits> | |
#include <iostream> | |
// This template is called 'or_combinator' | |
// it takes 2 function templates 'func1' , and 'func2' | |
// the arguments to each type function is template<typename> | |
// which means any typename | |
// you invoke them via func1<T>::value | |
// but they aren't instantiated until you ask for or_combinator<>::lambda<>::value | |
// | |
// they are also lazy! by nature of compiler laziness | |
// | |
template <template<typename> class func1, template<typename> class func2> | |
struct or_combinator{ | |
template<typename T> struct lambda{ | |
// notice that lambda | |
// is a true closure over the type functions func1 and func2 | |
// | |
// Obviously they have to have a member type called value | |
// That's what's called the return type of a template | |
// | |
constexpr static const bool value = func1<T>::value || func2<T>::value; | |
}; | |
}; | |
// templates to demonstrate late binding of function templates | |
template <typename T> struct is_ptr { | |
constexpr const static bool value = false; | |
}; | |
template <typename T> struct is_ptr<T*>{ | |
constexpr const static bool value = true; | |
}; | |
template <typename T> struct is_const { | |
constexpr const static bool value = false; | |
}; | |
template <typename T> struct is_const<const T> { | |
constexpr const static bool value = true; | |
}; | |
int main(){ | |
std::cout << "This late binding should blow your mind.\n Value: " | |
<< or_combinator<is_ptr,is_const>::lambda<const int>::value | |
<< std::endl | |
<< "The reason is true, is because is_const<const int>::value is true" | |
<< std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
g++ -std=c++11 template_lambda.cc
$ ./a.out
This late binding should blow your mind.
Value: 1
The reason is true, is because is_const::value is true