Skip to content

Instantly share code, notes, and snippets.

@psfrolov
Last active August 29, 2019 22:29
Show Gist options
  • Save psfrolov/c15788b10323bd4d5c54 to your computer and use it in GitHub Desktop.
Save psfrolov/c15788b10323bd4d5c54 to your computer and use it in GitHub Desktop.
Providing Explicit Specialisations for Non-Template Members of Class Template
// Tested with Clang 3.4, GCC 4.8.2.
#include <iostream>
#include <string>
template<typename T> class Foo {
public:
std::string Method();
static std::string StaticMethod();
static const std::string StaticData;
enum class Enum;
struct InnerStruct{ static const std::string StaticData; };
};
template<typename T> std::string Foo<T>::Method() {
return "std::string Foo<T>::Method() - primary template.";
}
template<> std::string Foo<char>::Method() {
return "std::string Foo<T>::Method() - "
"explicit specialisation for <char>.";
}
template<typename T> std::string Foo<T>::StaticMethod() {
return "std::string Foo<T>::StaticMethod() - primary template.";
}
template<> std::string Foo<char>::StaticMethod() {
return "std::string Foo<char>::StaticMethod() - "
"explicit specialisation for <char>.";
}
template<typename T> const std::string Foo<T>::StaticData{
"std::string Foo<T>::StaticData - primary template." };
template<> const std::string Foo<char>::StaticData{
"std::string Foo<char>::StaticData - "
"explicit specialisation for <char>." };
template<typename T> enum class Foo<T>::Enum { Primary = 0 };
template<> enum class Foo<char>::Enum { Specialised = 1 };
template<typename T> const std::string Foo<T>::InnerStruct::StaticData{
"std::string Foo<T>::InnerStruct::StaticData - primary template." };
template<> struct Foo<char>::InnerStruct{
static const std::string StaticData; };
const std::string Foo<char>::InnerStruct::StaticData{
"std::string Foo<char>::InnerStruct::StaticData - "
"explicit specialisation for <char>." };
int main() {
// Member function.
std::cout << Foo<int>().Method() << std::endl;
std::cout << Foo<char>().Method() << std::endl;
// Static member function.
std::cout << Foo<int>::StaticMethod() << std::endl;
std::cout << Foo<char>::StaticMethod() << std::endl;
// Static data member.
std::cout << Foo<int>::StaticData << std::endl;
std::cout << Foo<char>::StaticData << std::endl;
// Member enumeration.
std::cout << static_cast<int>(Foo<int>::Enum::Primary) << std::endl;
std::cout << static_cast<int>(Foo<char>::Enum::Specialised) << std::endl;
// Member class.
std::cout << Foo<int>::InnerStruct::StaticData << std::endl;
std::cout << Foo<char>::InnerStruct::StaticData << std::endl;
}
@psfrolov
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment