Last active
September 24, 2016 05:46
-
-
Save htfy96/3e79484d430c26dc81b6f7b06fc85b14 to your computer and use it in GitHub Desktop.
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 <iostream> | |
#include <utility> | |
#include <type_traits> | |
using namespace std; | |
template<int C> struct A | |
{ | |
const int val = C; | |
}; | |
template<typename T> struct B | |
{ | |
const bool is_a = false; | |
}; | |
template<int C> struct B<A<C>> // Oops, we need to know prototype of template A here | |
{ | |
const bool is_a = true; | |
}; | |
// Or better: | |
// In c.hpp: | |
template<typename T, int c> struct C | |
{ | |
}; | |
template<typename T> struct is_c | |
{ | |
static const bool val = false; | |
}; | |
template<typename T, int c> struct is_c<C<T, c>> | |
{ | |
static const bool val = true; | |
}; | |
// in d.hpp | |
template<typename T> struct MustNotC | |
{ | |
static_assert(!is_c<T>::val, "Cannot accept T as specialization of template C!"); | |
}; | |
// in e.hpp | |
template<typename T, bool = is_c<T>::val> struct E | |
{ | |
static const bool is_c = false; | |
}; | |
template<typename T> struct E<T, true> | |
{ | |
static const bool is_c = true; | |
}; | |
///////////////////////////////////////////////////////// | |
template<typename T> struct PolyBase | |
{ | |
static void f() { cout << "This is base function!" << endl; } | |
using type = T; | |
}; | |
template<typename T> struct PolyImpl: PolyBase<T> | |
{ | |
static const bool is_int = false; | |
}; | |
template<> struct PolyImpl<int>: PolyBase<int> | |
{ | |
static const bool is_int = true; | |
}; | |
int main() | |
{ | |
B<int> b1; | |
B<A<1>> b2; | |
cout << b1.is_a << endl; | |
cout << b2.is_a << endl; | |
MustNotC<int> d1; | |
//MustNotC<C<int, 2>> d2; | |
static_assert(false == E<int>::is_c, "test for E failed"); | |
static_assert(true == E<C<int, 3>>::is_c, "test for E failed"); | |
PolyImpl<double>::f(); | |
PolyImpl<int>::f(); | |
cout << PolyImpl<double>::is_int << endl; | |
cout << PolyImpl<int>::is_int << endl; | |
static_assert(is_same<typename PolyImpl<double>::type, double>::value, "Type mismatch"); | |
static_assert(is_same<typename PolyImpl<int>::type, int>::value, "Type mismatch"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment