Last active
August 29, 2015 14:21
-
-
Save gnarayan81/4a38605883a6d7d650fb to your computer and use it in GitHub Desktop.
The intent of this snippet is to illustrate the use and proscription of the typename keyword.
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
// The example I've chosen is from here: | |
// http://en.cppreference.com/w/cpp/language/template_specialization | |
#include <iostream> | |
template<class T> // primary template | |
struct is_void : /*typename*/ std::false_type // Despite having a qualified name, typename is now allowed here. | |
// It leads to the error, error: keyword 'typename' not allowed in this context (the base class is implicitly a type) | |
{ | |
struct s | |
{ | |
}; | |
}; | |
template<> // explicit specialization for T = void | |
struct is_void<void> : std::true_type | |
{ | |
}; | |
template <typename X> | |
void foo(void) | |
{ | |
typedef typename is_void<X>::s innser_s; // Without typename this will cause a compiler error. | |
// main.cpp: In function 'void foo()': | |
// main.cpp:18:13: error: need 'typename' before 'is_void<X>::s' because 'is_void<X>' is a dependent scope | |
// typedef is_void<X>::s innser_s; | |
} | |
int main() | |
{ | |
// for any type T other than void, the | |
// class is derived from false_type | |
std::cout << is_void<char>::value << '\n'; | |
// but when T is void, the class is derived | |
// from true_type | |
std::cout << is_void<void>::value << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment